Maddy said:
Thanks for the response. But I am a newbie. Could you please tell in a
little more detail. For beginning, I dont know what a UserControl
means. (Sorry, just started on c#). Would really appreciate step wise
explanation or if you can direct me where I can get the details as I
could not find anything either on the net or the vs2008 help.
Thanks
Nitin
You create a UserControl by right clicking on your project and select
Add->UserControl. Call this something like MyTreeView. You should end up
with the UserControl in design mode.
Drag a TreeView into the UserControl and set the Dock property to Fill.
Open the code view for the UserControl (right click the control and select
code view).
Override OnLoad and add the TreeNode-loading code inside. The code sample
below adds a selection of nodes from a string array. You can get the string
array from a file using File.ReadAllLines().
When you compile this you should be able to see "MyTreeView" as a control in
the ToolBox. If you drag this onto any control, the nodes should be filled
in the designer. You won't be able to click them though, and if the node
loading code is flawed, you need to add a control manually and run the
program to be able to debug it.
public partial class MyTreeView : UserControl
{
public MyTreeView()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
string[] nodes = new string[] {
"0|1|Hello",
"0|2|Goodbye",
"1|3|World",
"2|4|World" };
foreach (string s in nodes)
{
string[] data = s.Split('|');
string parentId = data[0];
string id = data[1];
string value = data[2];
if (parentId == "0")
treeView1.Nodes.Add(value).Tag = id;
else
{
TreeNode node = FindNode(treeView1.Nodes, parentId);
if (node != null)
node.Nodes.Add(value).Tag = id;
else
throw new InvalidOperationException("Incorrect data
order");
}
}
treeView1.ExpandAll();
}
private TreeNode FindNode(TreeNodeCollection treeNodeCollection, string
parentId)
{
foreach (TreeNode node in treeNodeCollection)
{
if (node.Tag.ToString() == parentId)
return node;
else
{
TreeNode parent = FindNode(node.Nodes, parentId);
if (parent != null)
return parent;
}
}
return null;
}
}