Asp. net2.0 reads data from the database to generate a hierarchical structured TreeView

Source: Internet
Author: User

Work requires navigation of a website. Tree navigation is required.
The nodes in the number of navigation are read from the database (Table associated), and the leaf nodes in the number are displayed according to the filtering type.
How can we dynamically generate Tree nodes and filter leaf nodes by type?
View the properties of the TreeView and you will find "PopulatNodesFromClient", which means whether to try to populate the node from the client.
After reading the explanation, of course, the value is "True ".
After "PopulatNodesFromClient" is assigned a value of "True", one attribute event in the TreeView is a TreeNodePopulate event, which is triggered when the TreeNode is being filled, when writing this event method, you can write and read the corresponding sub-node content from the database.
Therefore, when a node is added to the TreeNode, the event is triggered to fill its subnodes.
In this example, only the two-layer tree structure is displayed,
Protected void treeviewinclutreenodepopulate (object sender, TreeNodeEventArgs e)
{
If (e. Node. ChildNodes. Count = 0)
{
Switch (e. Node. Depth)
{
Case 0:
PopulateCategories (e. Node );
Break;
Case 1:
PopulateProducts (e. Node );
Break;
}
}
}

In addition, you can select the check box for this tree. One of the TreeView attributes is ShowCheckBoxes, and the value is Leaf, so that each Leaf node will display a check box.
The code for obtaining the selected node in the TreeView selection box is as follows:
Foreach (TreeNode node in TreeView1.CheckedNodes)
{
Arraystr. Add (node );
}

The code for this column is as follows:
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default3.aspx. cs" Inherits = "_ Default" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
& Nbsp; <asp: Label ID = "labelStatus" runat = "server" Font-Size = "12pt" Text = "test. "Width =" 87px "> </asp: Label>
<Br/>
<Asp: DropDownList ID = "DropDownList1" runat = "server"
Width = "119px" OnSelectedIndexChanged = "button#click" AutoPostBack = "True" AppendDataBoundItems = "True">
</Asp: DropDownList>
<Asp: Button ID = "Button1" runat = "server" Text = "" OnClick = "Button1_Click"/> <br/>
<Asp: Button ID = "submitbtn" runat = "server" OnClick = "submitbtn_Click" Text = ""/>
<Asp: Button ID = "Button2" runat = "server" OnClick = "Button2_Click" Text = "clear selection"/> <br/>
<Asp: Label ID = "Label1" runat = "server" Text = "Label" Width = "pixel PX"> </asp: Label> <br/>
<Asp: TreeView ID = "TreeView1" runat = "server" Font-Size = "12pt" MaxDataBindDepth = "2"
OnTreeNodePopulate = "treeviewappstreenodepopulate" Width = "371px" ShowCheckBoxes = "Leaf">
<Nodes>
<Asp: TreeNode PopulateOnDemand = "True" Text = "product list" Value = "product list"> </asp: TreeNode>
</Nodes>
</Asp: TreeView>

</Div>
</Form>
</Body>
</Html>

Using System;
Using System. Data;
Using System. Collections;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;

Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
SqlCommand sqlQuery = new SqlCommand (
"Select CategoryName, CategoryID From Categories ");
DataSet resultSet;
ResultSet = RunQuery (sqlQuery );
DropDownList1.DataSource = resultSet. Tables [0]. DefaultView;
DropDownList1.DataTextField = "CategoryName ";
DropDownList1.DataValueField = "CategoryID ";
DropDownList1.DataBind ();
}
Protected void treeviewinclutreenodepopulate (object sender, TreeNodeEventArgs e)
{
If (e. Node. ChildNodes. Count = 0)
{
Switch (e. Node. Depth)
{
Case 0:
PopulateCategories (e. Node );
Break;
Case 1:
PopulateProducts (e. Node );
Break;
}
}
}

Void PopulateCategories (TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand ();
If (Session ["typeorder"] = null) | (Session ["typeorder"]. ToString () = "All "))
{
SqlQuery. CommandText = "Select CategoryName, CategoryID From Categories ";
}
Else
{
SqlQuery. CommandText = "Select CategoryName, CategoryID From Categories where CategoryID = '" + Session ["typeorder"]. ToString () + "'";
}
DataSet resultSet;
ResultSet = RunQuery (sqlQuery );
If (resultSet. Tables. Count> 0)
{
Foreach (DataRow row in resultSet. Tables [0]. Rows)
{
TreeNode NewNode = new
TreeNode (row ["CategoryName"]. ToString (),
Row ["CategoryID"]. ToString ());
NewNode. PopulateOnDemand = true;
NewNode. SelectAction = TreeNodeSelectAction. Expand;
Node. ChildNodes. Add (NewNode );
}
}
}

Void PopulateProducts (TreeNode node)
{
SqlCommand sqlQuery = new SqlCommand ();
If (Session ["typeorder"] = null) | (Session ["typeorder"]. ToString () = "All "))
{
SqlQuery. CommandText = "Select ProductName From Products" +
"Where CategoryID = @ categoryid ";
SqlQuery. Parameters. Add ("@ categoryid", SqlDbType. Int). Value =
Node. Value;
}
Else
{
SqlQuery. CommandText = "Select ProductName From Products" +
"Where CategoryID = @ categoryid ";
SqlQuery. Parameters. Add ("@ categoryid", SqlDbType. Int). Value =
Node. Value;
}
DataSet ResultSet = RunQuery (sqlQuery );
If (ResultSet. Tables. Count> 0)
{
Foreach (DataRow row in ResultSet. Tables [0]. Rows)
{
TreeNode NewNode = new
TreeNode (row ["ProductName"]. ToString (), row ["ProductName"]. ToString (), null, "test. aspx? Id = "+ row [" ProductName "]. ToString ()," _ blank ");
NewNode. PopulateOnDemand = false;
NewNode. SelectAction = TreeNodeSelectAction. Expand;
Node. ChildNodes. Add (NewNode );
}
}
}

Private DataSet RunQuery (SqlCommand sqlQuery)
{
String connectionString =
ConfigurationManager. ConnectionStrings
["NorthwindConnectionString"]. ConnectionString;
SqlConnection DBConnection =
New SqlConnection (connectionString );
SqlDataAdapter dbAdapter = new SqlDataAdapter ();
DbAdapter. SelectCommand = sqlQuery;
SqlQuery. Connection = DBConnection;
DataSet resultsDataSet = new DataSet ();
Try
{
DbAdapter. Fill (resultsDataSet );
}
Catch
{
LabelStatus. Text = "Unable to connect to SQL Server .";
}
Return resultsDataSet;
}

Protected void submitbtn_Click (object sender, EventArgs e)
{
If (TreeView1.CheckedNodes. Count> 0)
{
Label1.Text = "you selected: <br> ";
ArrayList arraystr = new ArrayList ();
Foreach (TreeNode node in TreeView1.CheckedNodes)
{
Arraystr. Add (node );
}
If (Session ["selectednodes"]! = Null)
{
ArrayList arraystrswitch = new ArrayList ();
Arraystrswitch = (ArrayList) Session ["selectednodes"];
For (int m = 0; m <arraystr. Count; m ++)
{
Arraystrswitch. Add (TreeNode) arraystr [m]);
}
Session ["selectednodes"] = arraystrswitch;
}
Else
{
Session ["selectednodes"] = arraystr;
}

For (int k = 0; k <arraystr. Count; k ++)
{
Label1.Text + = (TreeNode) arraystr [k]). Value + "<br> ";
}
}
Else
{
If (Session ["selectednodes"]! = Null)
{
// Label1.Text = Session ["selectednodes"]. ToString ();
}
Else
{
Label1.Text = "You have not selected any content! ";
}
}

}
Protected void button#click (object sender, EventArgs e)
{
// DropDownList1.SelectedValue. ToString ();
// TreeView1.CollapseAll ();
Session ["typeorder"] = DropDownList1.SelectedItem. Value;
Response. Redirect ("Default3.aspx ");
}

Protected void Button2_Click (object sender, EventArgs e)
{
Session ["selectednodes"] = "";
Label1.Text = "";
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.