WinForm How to load database data into a tree

Source: Internet
Author: User

First, Introduction

For how to load the XML spanning tree in WinForm, I have written a detailed procedure in the previous article "How C # Implements loading a tree directory from XML and displays the full text." However, there are times when it is not possible to store large amounts of data in XML because XML is typically used for the delivery of small amounts of data. and the storage and transmission of big data we generally use specialized database management tools as the medium of delivery. Here, the point is, for the transfer of large amounts of data, we do not consider the rate of speed transfer problem here, we just to achieve the most basic function, so it is also convenient for beginners like me to understand.
Well, to say so much nonsense, began to formally enter the topic of our article:
"How do you WinForm to load database data into a tree"?
In order to better show the results we want, I will first show you this feature implementation diagram of a system I have done before, as shown below:

Well, it has been shown! If this is the effect you want, then I'll show you how to make this tree structure in the form of code.

Second, the realization process detailed

In order to achieve the above results, the work we need to do is divided into the following two steps:

  1. Building the database
    for the built database, we need to make it special. Because we're going to show the table of contents as a first level, when building database data, we need to articulate the relationship between the data-coding rules.
    Here I might say that I build this tree coding rules, you can also learn from each other:

    1.1. Encoding rules
    for different projects, the number of digits encoded is specific, and here My code is in the way-the prefix.
    When I define the number of digits, I take into account the different categories, the different levels, and the three parts.
    Encoding Rules: 1+12+4
    **1: First, class-differentiated. Here I divide: economic organization, social organization, or administrative district
    **12: administrative codes.
    It's exactly the same: 4+2+3+3
    4: The first four bits are the city level
    2: These two bits are county (city/district) level
    3: This three is the town (Township/Street/office) level
    3: These three are village (urban community/rural community) level
    **4: What kind of specific category, Which organization under which level
    I define this field as: OrgID.
    We only have this field or we can't build a tree, we also need the Name field (for text), and the parent field (used to build the link between the data – the inheritance relationship). Of course, you can build the fields you need based on your needs, and I won't say more about them here. I built the table as shown:

    Here's what we're looking at is how it's parent. Through this diagram, I believe that the relationship between the data of the inheritance, we are already familiar with. Well, after we've created the database, the next step is the code stage.

  2. Building the TreeView
    How do I build a treeview? This is another key issue.
    I'm using a control that comes with Visual Studio: the TreeView control. Here I might as well wordy, to show my design to everyone, easy for beginners to understand:

    Does it look very simple? Well, then we're going to build this treeview tree.
    2.1. Access to Data
    For how to get the data from the database I'm not going to explain this here, I am here in XML form from the server side to the client, with a DataTable object to store. What I do here is DataGridView this organizations tree when a cell is clicked, so we need to use a DataRow to record which rows of data are DataGridView.
    This code can be implemented from the DataGridView to the DataRow:
    dataRowView = gridX.Rows[rowIndex].DataBoundItem as DataRowView;    dataRow = dataRowView.Row;

This way we will get the data that exists in the DataTable object, and the row data that will be displayed exists in the DataRow.
By overloading the constructors, we pass these two arguments, and the constructor is as follows (the other two parameters, which I judge for different conditions, can be used without a tube):

         PublicOrganizations (DataTable transtable, DataRow Transrow,String Parent,StringCloumnname) {InitializeComponent (); Orgtable= NewDataTable (); Orgtable.TableName= "Record";//datatable table name, client and server-side consistent, establish contactOrgtable=transtable; GetRow=Transrow; Parentorgid= Global.userparentorg;//global is the static Class I declare, and the user obtains various static variables. Userorgid= Global.Userorgid; Name=Cloumnname; Functionsparent= Parent; }

Okay, next thing we need to load the data into the TreeView control, we can unload the Load event. The code is as follows:

    Private void Organizations_load(Objectsender, EventArgs e) {# region definition variablesList<treenode> TreeNodes;//DataRow DataRow;Datarow[] DataRows;            TreeNode TreeNode, Tempnode;            NameValueCollection parameter;            String str;            Treenode[] nodes; String Orgid,parentorgid;#endregion             # Region creation TreeTreeNodes =NewList<treenode> ();# region Add query root nodeDataRows = Orgtable.select ("[orgid]=\]"+ Userorgid +"\ '"); TreeNode =NewTreeNode (); Tag ="Orgid={0}&orgname={1}&parent={2}&fullname={3}"; Tag = String.Format (tag, datarows[0]["OrgID"], datarows[0]["OrgName"], datarows[0]["Parent"], datarows[0]["FullName"]); Treenode.name = convert.tostring (datarows[0]["OrgID"]); Treenode.text = convert.tostring (datarows[0]["OrgName"]);            Treenode.tag = Tag; Treenodes.add (TreeNode);//Add the root node to the TreeNodes listTREEVIEWX.NODES.ADD (TreeNode);//The phrase is to load the root node in the TreeView.             #endregion             # region Add child nodes             while(Treenodes.count >0) {TreeNode = treenodes[0];//each cycle is stripped of the first node, and the next loop is the second one .Treenodes.remove (TreeNode); Tag = Treenode.tag asString;                parameter = System.Web.HttpUtility.ParseQueryString (tag); str ="[parent]= ' {0} '"; str = String.Format (str, parameter["OrgID"]); DataRows = Orgtable.select (str); for(inti =0; i < datarows.length; i++) {tag ="Orgid={0}&orgname={1}&parent={2}&fullname={3}"; Tag = String.Format (tag, datarows[i]["OrgID"], datarows[i]["OrgName"], datarows[i]["Parent"], datarows[i]["FullName"]); Tempnode =NewTreeNode ();                    Tempnode.tag = Tag; Tempnode.name = convert.tostring (datarows[i]["OrgID"]); Tempnode.text = convert.tostring (datarows[i]["OrgName"]); Treenodes.add (Tempnode);//Add child nodes of parent node found aboveTREENODE.NODES.ADD (Tempnode);//TreeNode All sub-nodes under the Tempnode into its "under"}            }#endregion             #endregion             # region will record the org selected           //This code is judged according to the condition, the purpose is to make the default selection according to the condition.             if(Functionsparent = ="F005100")            {if(Name = ="OrgName") {Parentorgid = convert.tostring (getrow["parentorg"]); nodes = TreeViewX.Nodes.Find (Parentorgid,true);//Query the specific node                    if(Nodes. Length >0) {nodes[0]. Checked =true; }                }Else if(Name = ="Branchname") {OrgID = convert.tostring (getrow["OrgID"]); nodes = TreeViewX.Nodes.Find (OrgID,true);if(Nodes. Length >0) {nodes[0]. Checked =true; }                }            }Else{OrgID = convert.tostring (getrow["OrgID"]); nodes = TreeViewX.Nodes.Find (OrgID,true);if(Nodes. Length >0) {nodes[0]. Checked =true; }            }#endregion }

Actually here, the loading tree has been generated, then I write more, click "OK", then how to put the data into the control.

    Private void okButton_Click(Objectsender, EventArgs e) {# region definition variablesTreeNode SelectedNode;            List<treenode> nodes;            TreeNode TreeNode; NameValueCollection paramters;#endregion             #  RegionSelectedNode =NULL; nodes =NewList<treenode> ();//Note treeview.nodes is the root node in the acquired control.              for(inti =0; i < TreeViewX.Nodes.Count; i++) {nodes.            ADD (Treeviewx.nodes[i]); }//loop traversal, starting from the root node, and then each node to see if it is selected.              while(Nodes. Count >0) {TreeNode = nodes[0]; Nodes. Remove (TreeNode);if(treenode.checked = =true) {SelectedNode = TreeNode; Break; } for(inti =0; i < TreeNode.Nodes.Count; i++) {nodes.                ADD (Treenode.nodes[i]); }            }#endregion             # region reads the information and overwrites the data            if(SelectedNode! =NULL) {tag = Selectednode.tag asString;                Paramters = System.Web.HttpUtility.ParseQueryString (tag); getrow["OrgID"] = paramters["OrgID"]; getrow["OrgName"] = paramters["OrgName"]; }Else{getrow["OrgID"] =""; getrow["OrgName"] =""; } This. Close ();#endregion }

This is where our tree is basically built! The reason is that the basic build is complete, because when we click on the directory tree, the problem appears as shown:

Is that we can make multiple selections, but when we click OK, we get the first selection. The result we want is a single selection, and we can iterate over the selections in this form. How to achieve it?
With MSDN, we find an event called "Beforecheck" (which occurs before the tree node check box is selected), and its delegate is Treeviewcanceleventhandler (Beforecheck, Beforecollapse, BeforeExpand or BeforeSelect delegate event method). There is a remark in the note that says, "the event handler is called whenever the event occurs, unless the delegate is removed." ”
That is to say we actually call the default form of Beforcheck, we can call the Beforecheck event multiple times, that is, we can click to select multiple times. (In fact, we can get the solution according to the remark.) )
Then we could not help but have the following problems:
Question 1: How to resolve multiple selections?
We can re-write the Beforecheck event by first removing it, that is, it is not selectable, and then at the end of the call the modified Beforecheck.
Question 2: How to modify the selection in this dialog box
Recursive invocation
Okay, we got the solution. We can re-modify the Beforecheck event with the following code:

   Private void Treeviewx_beforecheck(Objectsender, TreeViewCancelEventArgs e) {list<treenode> nodes;            Int32 IntX; TreeNode TreeNode;//Prepare to manually modify check, close firstTreeviewx.beforecheck-=NewTreeviewcanceleventhandler (Treeviewx_beforecheck); nodes =NewList<treenode> (); for(IntX =0; IntX < TreeViewX.Nodes.Count; IntX = IntX +1) {nodes. ADD (Treeviewx.nodes[intx]); }//Traversal lookup             while(Nodes. Count >0) {TreeNode = nodes[0]; Nodes.                Remove (TreeNode); treenode.checked =false; for(IntX =0; IntX < TreeNode.Nodes.Count; IntX = IntX +1) {nodes. ADD (Treenode.nodes[intx]); }            }//e.node.checked = true;Treeviewx.beforecheck + =NewTreeviewcanceleventhandler (Treeviewx_beforecheck);//Recursive invocation}

At the end of the Load event, add:

 treeViewX.BeforeCheck += new TreeViewCancelEventHandler(treeViewX_BeforeCheck);

So far, our build tree is complete!

    ----祝好运!                                2015/05/07                                                      

WinForm How to load database data into a tree

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.