TreeView Control used for display hierarchical structured data e.g. XML. Here we can add new node in TreeView and also insert sub node in selected node.
Steps are given below:
Step1:-Take one windows Form and Design Form like below
Step 2:-write code on Form’s CS File
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace TreeView
{
public partial class TreeView : Form
{
public TreeView()
{
InitializeComponent();
}
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtNode.Text.Trim().Length == 0 && txtSubNode.Text.Trim().Length == 0)
{
MessageBox.Show("Please Enter Node Value.", "Data Entry Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
else if (txtNode.Text.Trim().Length != 0 && txtSubNode.Text.Trim().Length==0)
{
TreeNode parentNode = new TreeNode(txtNode.Text.Trim());//create an object of //Tree Node class and pass node name to the constructor of Tree Node.
treeView1.Nodes.Add(parentNode);//Adding parent node to a tree view.
txtNode.Clear();//Clear the text box control.
}
else if (treeView1.SelectedNode != null && txtSubNode.Text.Trim().Length != 0)
{
TreeNode childNode = new TreeNode(txtSubNode.Text);//Create an object of the child node and pass child node name to the constructor of Tree Node
treeView1.SelectedNode.Nodes.Add(childNode);//Add child node to the selected parent node
treeView1.ExpandAll();//Expand all the tree view control
txtSubNode.Clear();//clear the text box control.
}
else if (txtNode.Text.Trim().Length == 0 && txtSubNode.Text.Trim().Length != 0)
{
//show the message to select node to which child node should be added.
MessageBox.Show("Please Select Parent Node.", "Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//show the message to select node to which child node should be added.
MessageBox.Show("Please Select Parent Node.", "Warning Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
//select parent node
txtNode.Text = treeView1.SelectedNode.Text;
}
}
}
Output:-
javed khatri
13-Aug-2013send my email jaddi28@yahoo.com