How do I program a TreeView in asp.net? - asp.net

I have a tree view in my asp.net page, but I don't know how to program another childnodes. In my treeview I want to show data from my table "MyTable". My table is divided into id, name and level, but in the first node I want to show the first level, in the childnode I want to show the rows they are in second level and as another childnode I want to show the third level in "MyTable". I tried to do that with the following code:
Dim SqlCommand As String = String.Empty
Me.TreeView1.Nodes.Clear()
SqlString = "select name, id from MyTable"
Try
MsDb = New Clase_Coneccion
Dim Dr As OleDb.OleDbDataReader = MsDb.ConsultaDB(SqlString, MsDb.MsSqlServer)
While (Dr.Read())
Dim Nodo As New TreeNode
Nodo.Text = Dr("name").ToString()
Nodo.Value = Dr("id").ToString()
Nodo.PopulateOnDemand = (CInt(Dr("id")) > 0)
TreeView1.Nodes.Add(Nodo)
End While
Return
Catch ex As Exception
End Try
That's how I get the first nodes with all the names from "MyTable", but I don't know how to specify the childnodes for 2nd and 3d level. Any idea?

Related

VB. NET Add multiple ChildNodes in a Treeview

I have many records in a database and I need to populate my treeview dynamically like this: Below is just an example of what I need:
TreeView1.Nodes(a).ChildNodes.Add(New TreeNode("ChildNode " & b))
TreeView1.Nodes(a).ChildNodes(b).ChildNodes.Add(New TreeNode("ChildNode 2 lvl " & b))
I'm getting the records from a MySQL Db and I need to know how can I add multilevel ChildNodes into a loop For ... Next etc...
Do you have any suggestion or idea???
if you want to work with various levels of Treenodes you can use Find function
Dim TempNode As TreeNode = TreeView1.Nodes.Find("Node where I want to add SubNode", True).FirstOrDefault
TempNode.Nodes.Add("SubNode", "SubNode")
This way you can add SubNode to any Node you pick.
.Find("key",True)finds treenodes with following key and .FirstOrDefault picks first. Finally you just add new SubNode to Tempnode.
You considered you are getting it dynamically and from MySql. It may cause error like "Action beeing preformed on this control is being called from the wrong thread. Marshal to the correct thread using Contol.Invoke or Control.BeginInvoke to perform this action." Simply change TempNode.Nodes.Add("SubNode", "SubNode") to TreeView1.Invoke(Sub() TempNode.Nodes.Add("SubNode", "SubNode"))
EXAMPLE:
Dim comm As String = "SELECT * FROM YourTableName"
Dim SqlCmnd as SqlCommand = New SqlCommand(comm, YourMySqlConnection)
Dim READER As SqlDataReader
READER = SqlCmnd.ExecuteReader
While READER.Read
Dim NewNode As TreeNode = New TreeNode(READER.Item("origCategoryID"))
TreeView1.Nodes.Add(NewNode)
NewNode.Nodes.Add(READER.Item("categoryOrderID"))
End While
READER.Close()
EXAMPLE 2:
While READER.Read
If TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).Length > 0 Then
Dim NewNode As TreeNode = TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).FirstOrDefault
NewNode.Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
Else
TreeView1.Nodes.Add(READER.Item("OrigCatOrderID"), READER.Item("OrigCatOrderID"))
TreeView1.Nodes(READER.Item("OrigCatOrderID")).Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
End While

Read multiple items from list box to query information from a database

Ok so what I'm trying to do is allow the users of my web form in asp.net to select multiple assets from a list box. When they select these assets and press the select button it fires the following code which should run through the selected indices, query the DB for the description and asset tag's, and populate the Description and Asset tag boxes with those values. Working through this I've been able to get it to read the values from the database and populate the fields but it would only populate the value from the first selected item and it would just insert the same value equal to the number of times equal to the number of items selected in the inbox. I tried my current code to run through the indices a little better but it seems to be failing the If statement and I just can't figure out why. Any help is appreciated, thanks everyone!
Dim i As Integer
For i = 0 To lstAssets.GetSelectedIndices.Count
If lstAssets.Items(i).Selected = True Then
Dim str2 As String = lstAssets.Items(i).Value.ToString
Dim cs As New OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings("CSIWebUpd").ConnectionString)
Dim ds As String = cs.DataSource
Dim cn As OracleConnection = New OracleConnection("user id=webupd;password=webupd;data source=" + ds)
Dim sql As String = "SELECT description, tag FROM assets WHERE id = :id"
Dim cmd As New OracleCommand(sql, cn)
cmd.Parameters.Add(":id", OracleDbType.Varchar2).Value = str2
cmd.CommandType = CommandType.Text
cmd.BindByName = True
cn.Open()
Dim dr As OracleDataReader = cmd.ExecuteReader()
cmd.ExecuteNonQuery()
dr.Read()
desc = dr.GetString(0).ToString
ass = dr.GetString(1).ToString
If txtDescription.Text = Nothing Then
txtDescription.Text = dr.GetString(0).ToString
Else
txtDescription.Text = txtDescription.Text + Chr(13) + Chr(10) + dr.GetString(0).ToString
End If
If txtAsset.Text = Nothing Then
txtAsset.Text = dr.GetString(1).ToString
Else
txtAsset.Text = txtAsset.Text + Chr(13) + Chr(10) + dr.GetString(1).ToString
End If
cmd.Dispose()
cn.Close()
End If
Next i
UpdatePanel1.UpdateMode = UpdatePanelUpdateMode.Conditional
UpdatePanel1.Update()
I would work with the SelectedIndices values in this way
For Each i in lstAssets.GetSelectedIndices
Now i contains the index of the items selected not the offset of the GetSelectedIndices array
The GetSelectedIndices returns an array where every element of the array is the index in the Items collection where you have an item selected.
An example could explain better:
Supposing the the items selected are 1, 5 6 (Count=3), your code set the value of i to 0,1,2 and then uses that value to lookup the ID in the items collection, but the following check on lstAssets.Items(i).Selected found just the item at index 1 as selected. Instead using the for each approach you get the values 1,5,6.

asp.net grid view and dataList

I need help with a part of my website I'm coding. I have a listBox_Products which is populated with sqlServerDataSource. When I click on a product, it will display a corresponding picture along a gridview with productPrice and productName. The gridview is databound programmatically in the codebehind, on the indexChange event. I have a button, addToShoppingCart. On the button_Click event, I want to add the item the user chose to the shopping cart (it's on the same page), I have a second gridView, which received the item the user chose and displays it. This is where I'm stuck. I know I can't append to gridview, and I know it has to be databound. My logic is this: get the first item user chooses, add it to a datatable, insert into second gridview. Now if the user chooses another product, same logic, except this time, I would add a new row, and add the new data to the new row, keeping old row as well. Problem is I can't figure out how to do this. I'm not very experienced in datatable.
This is my code behind.
This is my code to get the product from sql server:
Private Sub GetProducts()
Dim TechShopConnectionString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
Dim TechCon As New SqlConnection(TechShopConnectionString)
Dim TechCmd As New SqlCommand()
Dim index As Integer = ListBox_Products.SelectedIndex()
TechCmd.CommandType = CommandType.StoredProcedure
TechCmd.CommandText = "GetAllProductInformationByID"
TechCmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
TechCmd.Connection = TechCon
Try
TechCon.Open()
GridView2.EmptyDataText = "No Records Found"
GridView2.DataSource = TechCmd.ExecuteReader()
GridView2.DataBind()
Catch ex As Exception
Throw ex
Finally
TechCon.Close()
TechCon.Dispose()
End Try
End Sub
This is my code to add item to the second gridview:
Protected Sub Button_AddToCart_Click(sender As Object, e As EventArgs) Handles Button_AddToCart.Click
Dim conn As SqlConnection = Nothing
Dim index As Integer = ListBox_Products.SelectedIndex()
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("Zapata_IT_DataBaseConnectionString").ConnectionString
conn = New SqlConnection(connString)
Dim cmd As SqlCommand = New SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "GetAllProductInformationByID"
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = index
cmd.Connection = conn
conn.Open()
Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dr2 As DataRow
dataTableCheckOut.NewRow()
dataTableCheckOut.Load(dr, LoadOption.OverwriteChanges)
GridView_CheckOut.DataSource = dataTableCheckOut
GridView_CheckOut.DataBind()
Catch ex As SqlException
Catch ex As Exception
Finally
conn.Close()
End Try
' Enter code here
As you can see I'm pretty lost. I know the logic is fine, but I cant figure out the code.
Any help would be appreciated.
If you want to keep the information about what is in the users cart from page to page (which you should want to), you should be saving the items in the users cart to the database. If you go to Amazon.Com, add something to your cart, then come back later, even on another compter, you can see the items in your cart, based on your login.
Since you know how to read data from the database, this should be easy for you. Just add the info to this new cart table and read it when you need it. Maybe every page shows the number of items and you just need the count but when viewing the cart of checking out, you need to show all the info.

Find nested gridview in user defined function

I'm having a problem populating a child gridview using a function I define. I keep getting the error "Object reference not set to an instance of an object". What am I doing wrong? Am I using the FindControl function incorrectly? It doesn't seem to find the child gridview.
Sub RecordsByZip()
Dim DBConn As New SqlConnection(Application("DBConn"))
Dim gv1 As GridView
gv1 = grdTotal
Dim gv2 As GridView
gv2 = DirectCast(gv1.FindControl("grdChild"), GridView)
Dim ZipCode = lbZip.SelectedItem
For Each ZipCode In lbZip.Items
If ZipCode.Selected = True Then
Dim cmdZip As SqlCommand = New SqlCommand("spPICAInsertTotals2", DBConn)
cmdZip.CommandType = CommandType.StoredProcedure
strZip = ZipCode.Text
strUser = Session("User")
Dim Zip As New SqlParameter("#Zip", SqlDbType.VarChar)
Zip.Value = strZip
cmdZip.Parameters.Add(Zip)
Dim UserID As New SqlParameter("#UserID", SqlDbType.Int)
UserID.Value = strUser
cmdZip.Parameters.Add(UserID)
DBConn.Open()
gv1.DataSource = cmdZip.ExecuteReader
gv1.DataBind()
gv1.Visible = True
DBConn.Close()
End If
Next
btnExport.Visible = True
lblmsg.Visible = False
' Dim DBConn = New SqlConnection(Application("DBConn"))
Dim cmdCounty As SqlCommand = New SqlCommand("spPICAInsertTotals", DBConn)
cmdCounty.CommandType = CommandType.StoredProcedure
'Dim gv As GridView = TryCast(e.Row.FindControl("grdChild"), GridView)
strUser = Session("User")
Dim UserID2 As New SqlParameter("#UserID", SqlDbType.Int)
UserID2.Value = strUser
cmdCounty.Parameters.Add(UserID2)
DBConn.Open()
gv2.DataSource = cmdCounty.ExecuteReader
gv2.DataBind()
gv2.Visible = True
DBConn.Close()
btnExport.Visible = True
lblmsg.Visible = False
lblInstructions.Visible = False
End Sub
First of all . . .
Just as a disclaimer, I normally use repeater controls instead of gridview controls.
But this may help you . . .
I can tell you that with repeater controls, if you want to find a nested repeater then you must look for them inside the item of the parent repeater to which they belong. Essentially, what you are trying to do with the code above, is find grdChild when there might actually be several grdChild (it is a nested gridview, after all). I'd be willing to bet this is where you're object reference error is occurring.
In other words, if you want to find the nested repeater with the ID nestedRepeater, and you know it is located in the first item of your main repeater (which in this case I've assigned to the myRepeater variable), you can do this:
Dim myItem as RepeaterItem = myRepeater.Items(0)
Dim Rep2 as Repeater = myItem.FindControl("nestedRepeater")
Using SqlDataAdapter and a DataSet (recommended)
Dim sa As New SqlDataAdapter(cmdCounty) 'Initialize the SqlDataAdapter and assign the SqlCommand object to it.
Dim ds As New DataSet() 'Initialize the DataSet (we will bind this to the gridview)
Try 'The Try/Catch statements help you to handle errors.
cmdCounty.Connection.Open() 'Open the connection to the database.
sa.Fill(ds) 'This statement uses the SqlDataAdapter to easily execute the SqlCommand (using the query specified in the SqlCommand object) and . . .
'. . .use that data to fill our dataset.
cmdCounty.Connection.Close() 'These statement close the connection and dispose of the SqlCommand object. Note: You may only need the dispose command.
cmdCounty.Dispose()
Catch ex As Exception
'Catch your error here.
cmdCounty.Connection.Close()
cmdCounty.Dispose()
End Try
gv2.DataSource = ds 'Set the datasource for your GridView control.
gv2.DataBind() 'Bind the data.
Using SqlDataReader and a DataTable
According to your comment, you're code is breaking when you assign the gridview to the cmd.ExecuteReader.
You will need to access your data using a method like this:
Dim rdr as SqlDataReader = cmdCounty.ExecuteReader() 'Declare the SqlDataReader and set it to handle your SqlCommand.
Dim dt as New DataTable 'Initialize a new DataTable. This is where we will place the information we read using the SqlDataReader.
'Make sure you add the columns...
dt.Columns.Add("firstColumnName") 'Create a column for each field you will be retrieving data from.
dt.Columns.Add("secondColumnName")
Dim r as DataRow 'Declare the variable r as a DataRow.
'You may want to insert the line "If rdr.HasRows Then" to check if any data was pulled before attempting to read it.
While rdr.Read() 'Loop through each row in the reader.
r = dt.NewRow() 'Set r to equal a new DataTable in the DataTable we created. Note: This does not actually add the row to the table.
r("firstColumnName") = rdr("firstColumnName") 'Set the values of each column in the current DataRow to equal their corresponding data read from SQL.
r("secondColumnName") = rdr("secondColumnName")
dt.Rows.Add(r) 'Add the DataRow r to the DataTable.
End While 'Loop back until there are no more rows.
gv2.DataSource = dt
gv2.DataBind()
Both of these examples assume you have already created your SqlCommand object and have assigned a working SQL query string and Connection object to it.

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

Resources