TreeView expanding wrong node - asp.net

I have a TreeView in a VB.NET/ASP.NET Application.
The TreeView is being Populated programmatically as the page loads. However, when i try and expand a node it is expanding the wrong node.
Example:I have a node with 5 children. Nodes one and two have children and when i try and expand node two it expands node one and when i try and expand node one it also expands node one.
I have tried re-organizing the structure of the TreeView and Also tried adding the nodes in one by one and still no luck.
Edit:
Below is the Relevant code from my TreeView :
For Each V2MaterialRow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Material Details'", connection)
Dim FormName As String = command.ExecuteScalar()
connection.Close()
V2MaterialNode = New TreeNode
V2MaterialNode.ToolTip = "V2 Material Details"
V2MaterialNode.Text = FormName & " " & V2MaterialRow("Version")
V2MaterialNode.Value = V2MaterialRow("Qno")
V2MaterialNode.ShowCheckBox = True
V2MaterialNode.NavigateUrl = "V2MaterialDetails.aspx?text=" + V2MaterialRow("Qno")
V2MaterialNode.Target = "_blank"
node.ChildNodes.Add(V2MaterialNode)
connection.Open()
command = New SqlCommand("Select * from Specallinone where qno='" + V2MaterialRow("Qno") + "'", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
For Each PurchaseOrderRow In DS.Tables("PurchaseOrder").Rows
PurchaseOrderNode = New TreeNode
PurchaseOrderNode.ToolTip = "Purchase Order"
PurchaseOrderNode.Text = "Purchase Order - " + PurchaseOrderRow("supplier") + " " + PurchaseOrderRow("Ordernumber")
PurchaseOrderNode.Value = PurchaseOrderRow("Qno")
PurchaseOrderNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + PurchaseOrderRow("Qno") + "&Jobno=" + PurchaseOrderRow("JobNumber") + "&Orderno=" + PurchaseOrderRow("Ordernumber") + "&text=" + Replace(PurchaseOrderRow("supplier"), "&", "$") + ""
PurchaseOrderNode.Target = "_blank"
V2MaterialNode.ChildNodes.Add(PurchaseOrderNode)
Next
Else
datareader.Close()
End If
connection.Close()
For Each LabelRow As DataRow In DS.Tables("AllinOne").Rows
Dim Labelnode = New TreeNode
Labelnode.ToolTip = "PO Labels"
Labelnode.Text = "PO Labels"
Labelnode.Value = LabelRow("Qno")
'Labelnode.ShowCheckBox = True
Labelnode.NavigateUrl = "GeneratePOLabels.aspx?text=" + LabelRow("Qno")
Labelnode.Target = "_blank"
Try
connection.Open()
command = New SqlCommand("Select * from purchaseorder where qno='" + LabelRow("Qno") + "' and Jobnumber<>''", connection)
datareader = command.ExecuteReader()
If datareader.HasRows = False Then
datareader.Close()
Exit For
Else
datareader.Close()
V2MaterialNode.ChildNodes.Add(Labelnode)
End If
Catch ex As Exception
Messagebox.Show("Error in Dispalying the Labels...")
Finally
connection.Close()
End Try
Next
Next
For Each MPORow In DS.Tables("ManualPO").Rows
Dim Supplier As String
connection.Open()
command = New SqlCommand("Select Distinct Supplier from ManualPurchaseOrder where ManualDetailsId='" + MPORow("ManualDetailsId").ToString + "' ", connection)
datareader = command.ExecuteReader()
While datareader.Read()
Supplier = Supplier + datareader.Item("Supplier") + ","
End While
datareader.Close()
connection.Close()
MPONode = New TreeNode
MPONode.Value = MPORow("ManualDetailsId")
MPONode.Text = "Manual PO " & MPORow("ManualDetailsId") & " Supplier:" & Supplier.ToString
Supplier = ""
node.ChildNodes.Add(MPONode)
Dim ManualPODetailsDa As New SqlDataAdapter("Select distinct supplier,Jobnumber,ordernumber,Qno from PurchaseOrder where Ordernumber in (Select Distinct OrderNumber From ManualPurchaseOrder where ManualDetailsId = '" + MPORow("ManualDetailsId") + "') ", connection)
Dim ManualPODetailsDs As New DataSet
ManualPODetailsDa.Fill(ManualPODetailsDs)
For Each ManualPODetailsDR As DataRow In ManualPODetailsDs.Tables(0).Rows
MPODNode = New TreeNode
MPODNode.Value = ManualPODetailsDR("OrderNumber")
MPODNode.Text = "Purchase Order - " + ManualPODetailsDR("supplier") + " " + ManualPODetailsDR("Ordernumber")
MPODNode.NavigateUrl = "PurchaseOrder.aspx?qno=" + ManualPODetailsDR("Qno") + "&Jobno=" + ManualPODetailsDR("JobNumber") + "&Orderno=" + ManualPODetailsDR("Ordernumber") + "&text=" + Replace(ManualPODetailsDR("supplier"), "&", "$") + ""
MPODNode.Target = "_blank"
MPONode.ChildNodes.Add(MPODNode)
Next
Next
For Each Takeoffrow In DS.Tables("AllinOne").Rows
connection.Open()
command = New SqlCommand("Select FormName from ISO where PageTitle='Take-Off-Sheets'", connection)
Dim FormName As String = command.ExecuteScalar()
TakeOffNode = New TreeNode
TakeOffNode.ToolTip = "Take Off Sheets"
TakeOffNode.Text = FormName & " " & Takeoffrow("Version")
TakeOffNode.Value = Takeoffrow("Qno")
TakeOffNode.ShowCheckBox = True
TakeOffNode.NavigateUrl = "TakeOffSheet.aspx?text=" + Takeoffrow("Qno")
TakeOffNode.Target = "_blank"
node.ChildNodes.Add(TakeOffNode)
command = New SqlCommand("Select count(*) from ManualTakeOffSheet where srecid in (Select Distinct Srecid from Specdetails where Quoteno='" + Takeoffrow("Qno") + "')", connection)
Dim MTS As Integer = 0
MTS = command.ExecuteScalar()
connection.Close()
If MTS > 0 Then
Dim ManualTakeoffnode As New TreeNode
ManualTakeoffnode.ToolTip = "Manual Take Off Sheets"
ManualTakeoffnode.Text = "Manual Take Off Sheets" & " " & Takeoffrow("Version")
ManualTakeoffnode.Value = Takeoffrow("Qno")
ManualTakeoffnode.NavigateUrl = "ManualTakeOffSheet.aspx?text=" + Takeoffrow("Qno")
ManualTakeoffnode.Target = "_blank"
TakeOffNode.ChildNodes.Add(ManualTakeoffnode)
End If
Next

Sometimes if you have a node which shares the same value as another node - unexpected behavior can occur (one node opening when the other is clicked)
Node values must be unique
Debug your code and ensure that all your nodes have a unique value.
The value will be stored in node.Value
In your case, the node.Value is populated from a table.
Ensure that TakeOffNode.Value = Takeoffrow("Qno") does not equal MPODNode.Value = ManualPODetailsDR("OrderNumber")

Related

Incorrect syntax near ',' (dbnull issue)

It suppose there is chart to be appeared. But, it doesnt as there is problem regarding dbnull issue. This happen when either one of three select statement has no data.
Dim user As String = Session("NoMatrik")
Dim resultId As Object = Session("max")
Dim idQuery = "select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 1 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 2 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 3"
conn.Open()
Dim cmdGetId As New SqlCommand(idQuery, conn)
cmdGetId.Parameters.AddWithValue("#matric", user)
Dim maxIDs As SqlDataReader = cmdGetId.ExecuteReader
Dim IDs As String = ""
While maxIDs.Read
IDs += maxIDs("id").ToString() + ", "
End While
maxIDs.Close()
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select tblResult.result_quiz_id as Quiz,count(TblAnswer.AnswerType) as answerCount , TblAnswer.AnswerType " +
"from TblResultDetail inner join TblAnswer on TblResultDetail.ResultDetail_Answer_Id = TblAnswer.AnswerId " +
"inner join tblResult on tblResult.resultid = TblResultDetail.ResultDetail_Result_Id " +
"where TblResultDetail.ResultDetail_Result_Id in (" + IDs + ") " +
"group by TblAnswer.AnswerType, tblResult.result_quiz_id order by TblAnswer.AnswerType"
Dim cmd As New SqlCommand(cmdString, conn)
If IsDBNull(resultId) Then
Label1.Visible = True
chrtResult.Visible = False
Else
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
Dim tempArr(0) As Double
Dim count As Double = dr1("answerCount")
tempArr(0) = count
Dim Type As String = dr1("AnswerType").ToString()
Dim level As Integer = dr1("Quiz")
chrtResult.Series(Type).Points(level - 1).YValues = tempArr
End While
End If
conn.Close()
End If
End Sub
an error, Incorrect syntax near '(' appear at line dr1 = cmd.ExecuteReader. So , how I want to fix this error?
Update your first query to exclude any Null values using a HAVING clause like so:
Dim idQuery = "select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 1 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 2 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 3 " +
"having max(resultid) is not null"
The having max(resultid) is not null will exclude any nulls in your UNION ALL.
If there are no IDs returned, you simply need to do a check on this before you execute your next block of code and do as #DmitriE suggests with the adding of quotes. Reorganise it to look like:
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
If IDs = "" Then
Label1.Visible = True
chrtResult.Visible = False
Else
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select ....."
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
' YOUR WHILE LOOP CODE HERE'
End While
End If
This should be
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
and then you need to remove last single quote.
in clause should follow this format: where x.id in ('id1', 'id2', 'idN')

The Microsoft Jet database engine cannot open the file

I am writing a code to query .CSV file using SQL below is my code which works perfectly fine
string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ fileDirectory + ";Extended Properties='text;HDR=YES;'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+"Order by 1 Desc";
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
con.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, con);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, con);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, con);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
con.Close();
But when I am trying to call the same code from the function by passing the file path which is retrieved from asp.net file upload control it does not work. Please see the code below.
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fupPath.HasFile)
{
string filename = Path.GetFileName(fupPath.FileName);
String csv_file_path = Path.Combine(Server.MapPath("~/Csv"), filename);
fupPath.SaveAs(csv_file_path);
Summery(csv_file_path);
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Response.Write("Rows count:" + csvData.Rows.Count);
//dtSummary(csvData);
}
}
protected void Summery(string fileName)
{
//string fileDirectory = #"C:\TechnicalTest\GskTest\Csv\SampleData.csv";
string fileDirectory = fileName;
//string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
// + System.IO.Path.GetDirectoryName(fileDirectory) + ";Extended Properties='text;HDR=YES;FMT=Delimited\'";
string sqlCust = "Select Count(order_id), order_id, contact_id from SampleData.csv "
+ "Group by order_id, contact_id "
+ "Order by 1 Desc";
string sqlProd = "Select Count(order_id), product_id from SampleData.csv "
+ "Group by product_id "
+ "Order by 1 Desc";
string sqlOrders = "Select Count(order_id) from SampleData.csv "
+ "Order by 1 Desc";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(fileDirectory) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
//OleDbConnection conn = new OleDbConnection(strCSVConnString);
conn.Open();
OleDbDataAdapter daCust = new OleDbDataAdapter(sqlCust, conn);
DataTable dtCust = new DataTable();
daCust.Fill(dtCust);
daCust.Dispose();
OleDbDataAdapter daProd = new OleDbDataAdapter(sqlProd, conn);
DataTable dtProd = new DataTable();
daProd.Fill(dtProd);
daProd.Dispose();
OleDbDataAdapter daOrders = new OleDbDataAdapter(sqlOrders, conn);
DataTable dtOrders = new DataTable();
daOrders.Fill(dtOrders);
daOrders.Dispose();
conn.Close();
}
You need to call a sheet name SheetName$ instead of file name SampleData.csv.
For example,
Select Count(order_id), order_id, contact_id from [SheetName$]
Normally, here is how you get a file path in ASP.Net, because you do not know the drive letter where your web application is hosted. In addition, you do not have access to a file located outside of web application.
var filePath = string.Format("{0}App_Data\\ExportImport\\{1}",
HttpRuntime.AppDomainAppPath, "SampleData.csv");

There is no row at position 0 error at asp.net

I was writing a web based program and this is my authentication page. It was working fine but suddenly it started to give that error.
Here is my code:
else if (LoginAs.SelectedValue == "Student")
{
string tableName = "StudentTable";
String name = "", surname = "", email = "";
string query = "Select level from " + tableName + " where ID='" + idBox.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
string level = Convert.ToString(cmd.ExecuteScalar());
CreateUser(con, tableName, ref name, ref surname, ref email);
query = "Select program from " + tableName + " where ID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
string program = Convert.ToString(cmd.ExecuteScalar());
MyGlobals.student = new Student(Convert.ToInt32(idBox.Text), "Active", email, name, surname, password, level, program);
MyGlobals.currentID = idBox.Text;
query = "Select * from RegisterTable where StudentID='" + idBox.Text + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0]; //ERROR COMES AT HERE
Course course = new Course(dr2["InstructorName"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
}
int num = (int)Application["OnlineUsers"];
Response.Redirect("Student.aspx");
}
Can anyone help me with this? Thanks in advance.
You don't specify where the exception is thrown but a very common reason for this (my opinion) is that your query doesn't return any results (or rows).

SQL ASP.NET INSERT troubles (part 2)

And i am back again.
I have asked a similair question before, but even with the help of the previous anwser and trying it with questionmarks or instead of Add i've tried AddWithValue i didn't have any luck.
I tried to change the txt_Naam to txt_Naam.Text, nothing.
Also putting [] around the columnnames, no luck.
It keeps giving me this "Syntax error in INSERT INTO statement.".
This time i got nowhere with the code below.
Probably something small, but i can't figure it out. (Again...)
protected void btn_final_Click(object sender, EventArgs e)
{
string fact_adres = txt_Naam.Text + "," + txt_Anaam.Text + "," + txt_Adres.Text + "," + txt_Toevoeg.Text + "," + txt_Pcode.Text + "," + txt_Plaats.Text + "," + txt_Email.Text ;
string fact_adres1 = txt_Naam1.Text + "," + txt_Anaam1.Text + "," + txt_Adres1.Text + "," + txt_Toevoeg1.Text + "," + txt_Pcode1.Text + "," + txt_Plaats1.Text + "," + txt_Email1.Text;
string a = "1";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; "
+ "Data Source=|DataDirectory|webwinkel.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (?, ?, ?);";
cmd.Parameters.Add("#factuur_adres", OleDbType.VarChar, 125).Value = fact_adres;
cmd.Parameters.Add("#verzend_adres", OleDbType.VarChar, 125).Value = fact_adres1;
cmd.Parameters.Add("#totaal_prijs", OleDbType.VarChar, 7).Value = a;
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
reader.Close();
}
catch (Exception exc)
{
Label1.Text = exc.Message;
}
finally
{
conn.Close();
Session["Winkelwagen"] = null;
}
}
You command text should be
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES (#factuur_adres,#verzend_adres, #totaal_prijs)";
Updated answer:
run your code with setting parameters, directly pass the value and check that it works or not
cmd.CommandText = "INSERT INTO Order (factuur_adres_id, verzend_adres_id, totaalprijs) VALUES ('abc','def','adf')";
When you are inserting don't you have to use
cmd.ExecuteNonQuery()
Instead of cmd.ExecuteReader() ??

advanced search page for web application using vb.net

i created a simple advanced search page for web application, i thought sharing it with you might help beginners
the following is an example of an advanced search page for an employee database using VB.Net
the following is the code behind page
Imports System.Data.OleDb
Partial Class searchme
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mydb As New OleDbConnection
mydb = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|employee.mdb;Persist Security Info=True")
mydb.Open()
Dim sqlstring = "select * from [dataview] where "
If MRNTextBox1.Text <> "" Then sqlstring = sqlstring + "[code] like '%" + CodeNameTextBox1.Text + "%' OR [EmployeeName] like '%" + CodeNameTextBox1.Text + "%' AND "
If GOVDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Governorate] ='" + GOVDDL.SelectedItem.Text + "' AND "
If genderddl.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Gender] ='" + genderddl.SelectedItem.Text + "' AND "
If DateEmploymentFrom.Text <> "" And DateEmploymentTo.Text <> "" Then sqlstring = sqlstring + "[DateEmployment] >= #" + DatumKonvert1.DK1(DateEmploymentFrom.Text) + "# AND [Datepresentation] <= #" + DatumKonvert1.DK1(DateEmploymentTo.Text) + "# AND "
If DepartmentDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Department] ='" + DepartmentDDL.SelectedItem.Text + "' AND "
sqlstring = Left(sqlstring, Len(sqlstring) - 5) + " order by " + OrderByDDL.SelectedItem.Text
Dim myds As New AccessDataSource
myds.DataFile = "~\App_Data\employee.mdb"
myds.SelectCommand = sqlstring
' Dim Mygrid As New GridView
Mygrid.DataSource = myds
Mygrid.DataBind()
' Me.form1.Controls.Add(Mygrid)
mydb.Close()
RecCount.Text = "Filtered Record Count = " + mygrid.Rows.Count.ToString
Session("dsource") = myds
Response.Redirect("sresults.aspx")
End Sub
End Class
you did a good job, also try the following
link text
link text

Resources