TreeView control usage and data binding

Source: Internet
Author: User

  First, Treeviewe is defined by more than one class, and the TreeView component is defined by the "TreeView" Class in the Namespace "System.Windows.Froms", where nodes (that is, node) are named spaces " System.Windows.Froms "TreeNode" in the definition. So creating a Treevirew object in the program is simply creating a "container" that can prevent the inspection. Adding a node to this container is actually adding a node object created from the "TreeNode" class, as well as deleting a node, that is, deleting a "TreeNode" object.

 Second, C # Operations Some common methods in the TreeView component as well as specific implementations:

Can be summed up as three basic operations: Join a child node, join a sibling node, and delete a node

1. Join a child node

The so-called child node is the next level node in the selected node. The process of joining a child node is to first locate the child nodes to be joined in the TreeView component , then create a node object, and then join the node object by using the Join method of the node in the Treeveiw class (that is: the Add () method). The following is the specific code that adds a child node to the TreeView1 component:

First determine if the position in the selected component is        if (Treeview1.selectednode = = null)        {            MessageBox.Show ("Select a Node", "Prompt message",            MessageBoxButtons.OK, messageboxicon.information);        }        else        {            //Create a Node object and initialize            TreeNode tmp;            TMP = new TreeNode ("node name");            Add a child node            TREEVIEW1.SELECTEDNODE.NODES.ADD (TMP) to the TreeView component;            Treeview1.selectednode = tmp;            Treeview1.expandall ();        

2. Join the sibling node

  

The so-called sibling node is the node at the peer of the selected node. The method of joining the sibling node and the method of joining the child node are basically the same, but there is a slight difference in the final implementation method. The specific steps to join the sibling node are first to determine the location of the sibling nodes to be joined, then define a node object, and finally call the method joined to the sibling node in the TreeView class to join the node object. The biggest difference between joining a sibling node and joining a child node is this last step. I hope readers can pay attention. Here is the specific code that joins a sibling node in the TreeView component:

First, determine if the position of the node in the selected component is        if (Treeview1.selectednode = = null)        {            MessageBox.Show ("Select a Node", "Prompt message",            MessageBoxButtons.OK, messageboxicon.information);        }        else        {            //Create a Node object and initialize            TreeNode tmp;            TMP = new TreeNode (TextBox1.Text);            Join the sibling node            TREEVIEW1.SELECTEDNODE.PARENT.NODES.ADD (TMP) in the TreeView component;            Treeview1.expandall ();        

3. Delete a node

Deleting a node deletes the selected node in the TreeView component, the node can be a child node or a sibling node, but regardless of the nature of the node, you must ensure that the node you want to delete does not have a next-level node, or you must first delete all the next-level nodes in this node before you delete the node. Deleting a node is slightly simpler than the two above, by first determining whether the node to be removed has a next-level node, or, if it does not exist, by calling the Remove () method in the TreeView class to delete the node. Here is the specific code to remove the nodes in the TreeView component:

Some other common operations for 4.TreeView components:

< I >. Expand all nodes:

To expand all nodes in the TreeView component, first locate the selected node pointer on the root node of the TreeView component, and then invoke the ExpandAll method of the selected component, following the specific code:

Locate the root node Treeview1.selectednode = treeview1.nodes [0];//Expand all nodes in the component TreeView1.SelectedNode.ExpandAll ();

< II > Expand the next Level node of the selected node:

It is not necessary to use the ExpandAll () method because only the next level node is expanded. To expand the next level node only needs to call the expand () method, the following is the specific implementation code:

TreeView1.SelectedNode.Expand ();

    

< III > Collapse all nodes:

Collapse all nodes and expand all nodes is a set of interoperability, the implementation of the idea is roughly the same, the collapse of all nodes is also the first to locate the selected node pointer on the root node, and then invoke the selected component of the collapse () on it, the following is the specific implementation code:

Third, examples

Using System, using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.    Forms; using System.Data; namespace a complete understanding of how the TreeView component is used {////Form1 Summary description.        public class Form1:form {private TreeView treeView1;        Private Button button1;        Private Button button2;        Private Button Button3;        Private MenuItem menuItem2;        Private MenuItem menuItem3;        Private MenuItem menuItem4;        Private ContextMenu contextMenu1;        Private TextBox TextBox1;        Private Label Label1;        The required designer variables.        Private System.ComponentModel.Container components = null;        Public Form1 () {//Initialize the component InitializeComponent () in the form;        ///Clean up all the resources being used. protected override void Dispose (bool disposing) {if (disposing) {if (c Omponents = null) {components.       Dispose ();         }} base.        Dispose (disposing); } private void InitializeComponent () {//initialization code (slightly)} [STAThread] static Voi        D Main () {Application.Run (New Form1 ());  private void Addchildnode () {//first determines if the position in the component is selected if (Treeview1.selectednode = = NULL {MessageBox.Show ("Please select a node", "Prompt Message", MessageBoxButtons.OK, Messageboxico            N.information); } else {if (TextBox1.Text! = "") {//Creates a node object and initially                    Initiation of TreeNode tmp;                    TMP = new TreeNode (TextBox1.Text);                    Add a child node TREEVIEW1.SELECTEDNODE.NODES.ADD (TMP) to the TreeView component;                    Treeview1.selectednode = tmp;                Treeview1.expandall ();           } else     {MessageBox.Show ("TextBox component must fill in the node name!                    "," hint message ", MessageBoxButtons.OK, MessageBoxIcon.Information);                return; }}} private void Addparent () {//first determine if the position of the node in the selected component is if (treeView1 . SelectedNode = = null) {MessageBox.Show ("Please select a node", "Prompt Message", MessageBoxButtons.OK, Messageb            Oxicon.information); } else {if (TextBox1.Text! = "") {//Creates a node object and initially                    Initiation of TreeNode tmp;                    TMP = new TreeNode (TextBox1.Text);                    Join the sibling Node TREEVIEW1.SELECTEDNODE.PARENT.NODES.ADD (TMP) in the TreeView component;                Treeview1.expandall (); } else {MessageBox.Show ("TextBox component must fill in the node name! "," hint message ", MessageBoxButtons.OK, MessageBoxIcon.Information);                   return;        }} TreeNode tnode = new TreeNode (TextBox1.Text); private void Treeview1_mousedown (object sender, MouseEventArgs e) {if (E.button =        = Mousebuttons.right) Contextmenu1.show (this, new Point (e.x, e.y)); private void Button1_Click (object sender, System.EventArgs e) {Treeview1.selectedn Ode.        Expand (); private void Menuitem2_click (object sender, System.EventArgs e) {Addchildnode ()        ;        } private void Menuitem3_click (object sender, System.EventArgs e) {addparent (); private void Menuitem4_click (object sender, System.EventArgs e) {//Determines whether the selected node There is a next level node if (TreeView1.SelectedNode.Nodes.Count = = 0)//delete node TreeView1.SelectedNode.Remo     ve ();       Else MessageBox.Show ("Delete the child nodes in this node first!")        "," hint message ", MessageBoxButtons.OK, MessageBoxIcon.Information);            private void Button2_Click (object sender, System.EventArgs e) {//Locate root node            Treeview1.selectednode = treeview1.nodes [0];        Expand all nodes in the component TreeView1.SelectedNode.ExpandAll ();            private void Button3_Click (object sender, System.EventArgs e) {//Locate root node            Treeview1.selectednode = treeview1.nodes [0];        Collapse all nodes in the Assembly TreeView1.SelectedNode.Collapse (); }    }}

Iv. Data Binding

The default expansion tree level, 0 is not to expand, 1 is to expand the level;

1. Recursive method

public partial class _default:system.web.ui.page{    private void Loadtree (TreeNode parentnode)    {        list< chinastates> list = new CHINABF (). Selectbycode (Parentnode.value);        if (list. Count = = 0)        {            return;        }        foreach (chinastates item in list)        {            TreeNode childnode = new TreeNode ();            Childnode.text = Item. AreaName;            Childnode.value = Item. AreaCode;            PARENTNODE.CHILDNODES.ADD (Childnode);            Loadtree (Childnode);        }    }    protected void Page_Load (object sender, EventArgs e)    {        TreeNode root = new TreeNode ();        Root. Text = "China";        Root. Value = "0001";        TREEVIEW1.NODES.ADD (root);        Loadtree (root);}    }

2.for nesting

public void Treebind () {TreeNode root = new TreeNode (); Root.    Text = "Han enterprise Data Tong Software Co., Ltd."; Root.    Value = "H001"; Root.    SelectAction = Treenodeselectaction.none;    TREEVIEW1.NODES.ADD (root); list<department> list = new Function ().    Selectpart ();    List<worker> data=new list<worker> ();        foreach (Department item in list) {TreeNode Firstnode = new TreeNode (); Firstnode.text = Item.        Department1; Firstnode.value = Item.        Departcode;        Firstnode.selectaction = Treenodeselectaction.none; Root.        Childnodes.add (Firstnode); List<worker>arr= new Function (). Selectworker (item.        DEPARTMENT1);            foreach (Worker workers in arr) {TreeNode child = new TreeNode (); Child. Text = workers.            Wname; Child. Value = workers.            Wid.tostring (); Child.            SelectAction = Treenodeselectaction.none;        FIRSTNODE.CHILDNODES.ADD (child); }    }}

3. Traverse all child nodes to find the selected item

protected void Button1_Click (object sender, EventArgs e) {    list<treenode> listnodes = new list<treenode> ();    foreach (TreeNode node in treeview1.nodes)    {        if (node! = null)        {            findchecknode (node, listnodes);        }        Else        {            return;}}    } private void Findchecknode (TreeNode node, list<treenode> listnodes) {    if (node. Checked)    {        listnodes.add (node);    }    foreach (TreeNode childnode in node. ChildNodes)    {        Findchecknode (Childnode, listnodes);}    }

  

TreeView control usage and data binding

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.