Sunday, January 30, 2011

How to list items in categories and subcategories in treeview

Hello everyone -
Today I will explain how I solved problem I had with listing multiple subcategories in a treeview control on asp.net page.
I had problem where I was suppose to display files listed in categories which were populated by the user and then the files under each category were uploaded on the server from a user.
The files were all in one folder per company, and there was a table in the database where I was saving the info about which files are going where, under which name and which user.
So, I started to get my hands dirty.
First, I wanted to get all the categories which were created and there was a record for them in the database.
I did a simple query for doing that, and then I fetch the data from the table to a node in the treeview:

string getCategories = "SELECT Category FROM Categories";
SqlCommand commCat = new SqlCommand(getCategories, conn);
comm.CommandTimeout = 0;
comm.CommandType = CommandType.Text;
SqlDataReader rdrCat = commCat.ExecuteReader();
while (rdrCat.Read())
{
if (rdrCat.HasRows)
{
catNode = new TreeNode();
catNode.Text = rdrCat["Category"].ToString();
catNode.Value = rdrCat["Category"].ToString();
tvDocuments.Nodes.Add(catNode);
}
}


Once I had all the categories created in the treeview I went to get all the files for each category.
I created stored procedure which gets all the files and their categories from the info stored in the database.
Once I had all the info about the files and their respected categories I started looping through the nodes in the treeview and if the node had the same name as the category for the file, add the file to that category.
The loop was going like this:

foreach (DataRow dt in tblTreeView.Rows)
{
foreach (TreeNode node in tvDocuments.Nodes)
{
if (node.Text.Equals(dt[0].ToString()))
{
fileNode = new TreeNode();
fileNode.Text = dt[1].ToString();
fileNode.NavigateUrl = "../downloading.aspx?file=" + dt[1].ToString() + "&user=" + userID;
node.ChildNodes.Add(fileNode);
}
}
}


Since the file nodes were also hyperlink for downloading the documents I set the navigate url to the appropriate page for downloading along with the filename and the user id.

Thanks for reading and comments always appreciated.

1 comment: