Sunday 8 May 2011

TreeView Control Using C#

TreeView Control
TreeView Control is used for showing hierarchical structured data visually e.g.. XML.
Example for TreeView Control In shown Below -This is image of Explorer in Windows that show files and folder in tree view.
                                       


   
Working With TreeView Control
Drag and drop TreeView Control from toolbox, Like shown in below image.
 In following example I have taken a tree list view of colleges name for this i have taken ContextMenuChild and Parent for adding nodes. And you can also add by on clicking add child button and add sibling event.
Code for Add Child is given Below

private void buttonAddChild_Click(object sender, System.EventArgs e)
        {
            if (textBox1.Text != "")
                AddChildToTheNode();
            else
            {
                MessageBox.Show("Enter the Node Text to be added");
                textBox1.Focus();
            }
        }

 private void AddChildToTheNode()
        {
            TreeNode tnode = new TreeNode(textBox1.Text);
            treeView1.SelectedNode.Nodes.Add(tnode);
            treeView1.ExpandAll();
            if (treeView1.SelectedNode.Nodes.Count > 1 && treeView1.SelectedNode.ForeColor != Color.Blue)
                treeView1.SelectedNode.ForeColor = Color.Brown;
        }
Code for Menu Item Click

private void menuItem2_Click(object sender, System.EventArgs e)
        {
            if (textBox1.Text != "")
                AddChildToTheNode();
            else
            {
                MessageBox.Show("Enter the Node Text to be added");
                textBox1.Focus();
            }
        }
Code for Add Sibling

private void btnAddSibling_Click(object sender, System.EventArgs e)
        {
            if (textBox1.Text != "")
                AddSiblingToTheNode();
            else
            {
                MessageBox.Show("Enter the Node Text to be added");
                textBox1.Focus();
            }
        }
 

private void AddSiblingToTheNode()
        {
            TreeNode tnode = new TreeNode(textBox1.Text);
            tnode.ForeColor = Color.Brown;
            treeView1.SelectedNode.Parent.Nodes.Add(tnode);
        }
                                              
Code For Deleting Child and Sibling.

 private void buttonDeleteParent_Click(object sender, System.EventArgs e)
        {
            DeleteNode();
        }
private void DeleteNode()
        {
            if (treeView1.SelectedNode.Nodes.Count == 0)
                treeView1.SelectedNode.Remove();
            else
                MessageBox.Show("First Remove all the child nodes");
        }

1 comment: