TreeView binding and TreeView binding

Source: Internet
Author: User

TreeView binding and TreeView binding

Recently, I encountered the TreeView database binding problem. It did take me a few days, especially the step-by-step binding of multi-level nodes. In the first place, I found that all the page loading was stuck, this is really a headache. So let's take a look at what you need, so as not to let everyone go.

1. Only data tables of the first-level nodes are bound.

Some code:

Protected void treeviewbind () {string sqlstr = ConfigurationManager. appSettings ["constr"]; SqlConnection con = new SqlConnection (sqlstr); con. open (); string strfac = "select * from tDepartment"; SqlDataAdapter ada = new SqlDataAdapter (strfac, con); DataTable dt = new DataTable (); ada. fill (dt); string id = "Department"; string text = "Department"; Bind_ TV (dt, id, text); dt. dispose (); ada. dispose (); con. close ();} protected void Bind_ TV (DataTable dt, string id, string text) // recursive binding of TreeView {DataView dv = new DataView (dt ); // Save the able to DataView to filter the data TreeNode tn; // create a TreeView node (TreeNode ), to add the retrieved data to the node, foreach (DataRowView row in dv) {tn = new TreeNode (); // create a new node (named as an instance) tn. value = row [id]. toString (); // Value of the node, which is generally the id Value of the database tn. text = row [text]. toString (); // The Node Text. The Node Text displays TreeView1.Nodes. add (tn); // Add the node to the TreeView }}




2. Step-by-Step loading and binding of multi-level nodes

Related code:

<asp:TreeView ID="TreeView1" runat="server" ImageSet="Simple" CssClass="gridview_m"                                                OnSelectedNodeChanged="TreeView1_SelectedNodeChanged" NodeIndent="35" ExpandDepth="0"                                                ShowLines="True" OnTreeNodeExpanded="TreeView1_TreeNodeExpanded">                                            </asp:TreeView>

Protected void bind () // data binding of TreeView {string sqlstr = ConfigurationManager. appSettings ["constr"]; SqlConnection conn = new SqlConnection (sqlstr); conn. open (); string sqlsel = "select * from tDataSheetDirectory"; SqlCommand cmd = new SqlCommand (sqlsel, conn); SqlDataAdapter sda = new SqlDataAdapter (cmd ); dataTable dt = new DataTable (); sda. fill (dt); string id = "DataSheetDirectoryID"; string text = "DirectoryName"; string pid = "FatherID"; DataView dvtop = new DataView (dt); // Add the root node TreeNode tntop = new TreeNode (); dvtop. rowFilter = "FatherID is null"; foreach (DataRowView row in dvtop) {tntop. value = row [id]. toString (); tntop. text = row [text]. toString (); TreeView1.Nodes. add (tntop);} sda. dispose (); cmd. dispose (); conn. close (); Bind_ TV (dt, tntop, tntop. value, id, pid, text);} protected vo Id Bind_ TV (DataTable dt, TreeNode p_Node, string pid_val, string id, string pid, string text) // recursive binding of TreeView {DataView dv = new DataView (dt ); // Save the able to DataView to filter data // create a TreeNode node for the TreeView, so that the retrieved data can be added to the node. // The following is a Trielement operator, if the parent id is empty, it is the query condition for building "parent id field is null". Otherwise, the query condition for "parent id field = parent id field value" is string filter = string. isNullOrEmpty (pid_val )? Pid + "is null": string. format (pid + "= '{0}'", pid_val); dv. rowFilter = filter; // use DataView to filter data and select the data foreach (DataRowView row in dv) {TreeNode tn = new TreeNode (); tn. value = row [id]. toString (); // The Value of the node Value is tn. text = row [text]. toString (); // node Text value p_Node.ChildNodes.Add (tn); // Add the node to the upper-level node} protected void TreeView1_SelectedNodeChanged (object sender, EventArgs e) {ViewState ["DataSheetState"] = 0; int directoryid = Convert. toInt32 (this. treeView1.SelectedNode. value); string sqlstr = ConfigurationManager. appSettings ["constr"]; SqlConnection con1 = new SqlConnection (sqlstr); con1.Open (); string strfac1 = "select * from tDataSheetDirectory where DataSheetDirectoryID = '" + directoryid + "'"; sqlCommand cmd1 = new SqlCommand (strfac1, con1); SqlDataReader dr1 = secrets 1.executereader (); dr1.Read (); if (dr1.HasRows) {// Label1.Text = dr1 ["DirectoryName"]. toString () ;}dr1.dispose (); Prepare 1.dispose (); con1.Close (); // ViewState ["DataSheetDirectoryID"] = this. treeView1.SelectedNode. value; // GridViewBind ("select * from tDataSheet where FatherDirID = '" + this. treeView1.SelectedNode. value + "'"); GridViewBind ("select tDataSheetDirectory. *, tDataSheet. * from tDataSheetDirectory, tDataSheet where tDataSheet. fatherDirID = '"+ this. treeView1.SelectedNode. value + "'and tDataSheet. fatherDirID = tDataSheetDirectory. dataSheetDirectoryID and tDataSheetDirectory. hidden = ''"); for (int I = 0; I <this. treeView1.Nodes. count; I ++) {// if (this. treeView1.SelectedValue = this. treeView1.Nodes [I]. value) {// if the root node is selected, expand this. treeView1.SelectedNode. expanded = true;} else {// If the selected node is not the root node for (int j = 0; j <this. treeView1.SelectedNode. parent. childNodes. count; j ++) {// this causes all peer nodes of the selected node to contract this. treeView1.SelectedNode. parent. childNodes [j]. collapseAll () ;}/// then expand the selected node and all its parent nodes // this. treeView1.SelectedNode. parent. expanded = true; this. treeView1.SelectedNode. expanded = true ;}} protected void treeviewinclutreenodeexpanded (object sender, TreeNodeEventArgs e) {string sqlstr = ConfigurationManager. appSettings ["constr"]; SqlConnection conn = new SqlConnection (sqlstr); conn. open (); TreeNode exnode = e. node; // expand the Node int fid = Convert. toInt32 (exnode. value); // expand the node ID string sqlsel = "select * from tDataSheetDirectory"; SqlCommand cmd = new SqlCommand (sqlsel, conn); SqlDataAdapter sda = new SqlDataAdapter (cmd ); dataTable dt = new DataTable (); sda. fill (dt); NodeExpand (dt, exnode, fid);} protected void NodeExpand (DataTable dt, TreeNode p_node, int pid) {int nextnodec = p_node.ChildNodes.Count; // number of lower-level nodes for (int I = 0; I <nextnodec; I ++) {TreeNode tn = p_node.ChildNodes [I]; tn. childNodes. clear (); int nodevalue = Convert. toInt32 (tn. value); DataView Newcastle = new DataView (dt); // you can call this operation to obtain the whole table. rowFilter = "FatherID = '" + nodevalue + "'"; TreeNode tnn; // subnode foreach (DataRowView rown in OPC) {tnn = new TreeNode (); tnn. text = rown ["DirectoryName"]. toString (); tnn. value = rown ["DataSheetDirectoryID"]. toString (); tn. childNodes. add (tnn );}}}



C # treeview recursively bind data

{
SqlDataAdapter adp = new SqlDataAdapter ("select * from tb_table", connString );
DataTable dtData = new DataTable ();
Adp. Fill (dtData );
TreeView TV; // tree control
TV. Nodes. Clear ();
// Obtain Level 1 Data
DataRow [] drRoot = dtData. Select ("len (varid) = 3 ");
Foreach (DataRow dr in drRoot)
{
TreeNode tn = new TreeNode ();
Tn. Text = dr ["Name"]. ToString ();
AppendChild (tn, dr ["varid"]. ToString ());
TV. Nodes. Add (tn );
}
}
// Recursively bind data
Private void AppendChild (TreeNode tnParent, string varid)
{
DataRow [] drs = dtData. Select ("substring (varid, 0," + varid. length + "and len (varid) =" + varid. length + 3 ));
Foreach (DataRow dr in drs)
{
TreeNode tn = new TreeNode ();
Tn. Text = dr ["Name"]. ToString ();
AppendChild (tn, dr ["varid"]. ToString ());
TnParent. ChildNodes. Add (tn );
}
}

This is probably the case. Let's modify it.

C # Is the TreeView bound to the database?

Recursive Method.
// <Summary>
/// TreeView Data Binding
/// </Summary>
/// <Param name = "list"> </param>
Protected void CreateTreeView ()
{
TreeNode rootNode = new TreeNode ();
RootNode. Text = "all ";
RootNode. Value = "-1 ";
BasicTypeTreeView. Nodes. Add (rootNode );

BasicInformationManager BasicManager = new BasicInformationManager ();
Var tlist = BasicManager. GetAllBasicInfoTypes ();
Foreach (Model. BasicInforType mtype in tlist)
{
If (mtype. ParentID = 0)
{
TreeNode Node = new TreeNode ();
// Add the root node
Node. Text = mtype. BasicTypeName;
Node. Value = mtype. ID. ToString ();
Node. ToolTip = "encoding" + mtype. BasicCode;
GetSubNode (ref Node, mtype. ID );
RootNode. ChildNodes. Add (Node );
}
}
}

/// <Summary>
/// Obtain the treeView subnode
/// </Summary>
/// <Param name = "node"> </param>
/// <Param name = "item"> </param>
Public void getSubNode (ref TreeNode node, int item)
{
BasicInformationManager... the remaining full text>

Related Article

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.