tags:

views:

22

answers:

2

Hi all,

My problem is, I'm using a TreeView in a UserControl. While debugging, I can see the results are adding in the TreeView but it's not happening when I'm using that UserControl onto my MainForm. The UserControl containing the TreeView remains blank during runtime of the main application. I've also referenced the UserControl project with my Main project. Here I'm giving my code for helping me out.

Thanks in advance.

Code:

In the UserControl class:

public override void Refresh()
{
   PopulateTreeView();
}
private void PopulateTreeView()
{
   TreeNodeCollection treeNodeCollection;   
   treeNodeCollection = CreateParentNode("My Information");
   CreateChildNode(treeNodeCollection, "Name");
   CreateChildNode(treeNodeCollection, "Address");
   this.Update();
   myTreeView.ExpandAll();
}
private TreeNodeCollection CreateParentNode(string parentNode)
{
   TreeNode treeNode = new TreeNode(parentNode);
   myTreeView.Nodes.Add(treeNode);
   return treeNode.Nodes;
}
private void CreateChildNode(TreeNodeCollection nodeCollection, string itemName)
{
   TreeNode treeNode = new TreeNode(itemName);
   nodeCollection.Add(treeNode);
}

In my MainForm:

private void button1_Click(object sender, EventArgs e)
{
   UserControl userControl = new UserControl();
   userControl.Refresh();
}
A: 

In the Click-Event of the Button you are creating a new UserControl and not actually using the UserControl that is placed on your MainForm.

Either, you have to call Refresh() on the UserControl that´s on your MainForm, or you have to add the newly created UserControl to the ControlsCollection of the MainForm.

When you added the UserControl with the Designer of VisualStudio, the MainForm should contain a variable with the name userControl1. On this you call Refresh(). Then you should see the expected result and the populated TreeView.

private void button1_Click(object sender, EventArgs e)
{
  userControl1.Refresh();  // Assume that the name of UserControl is userControl1
}

If you want to use a new UserControl every time you click the Button, you have to add the control to the ControlsCollection of the MainForm. But then you have to perform some layout logic.

private void button1_Click(object sender, EventArgs e)
{
  UserControl userControl = new UserControl();
  userControl.Refresh();
  this.Controls.Add(userControl);
  // Perform layout logic and possibly remove previous added UserControl
}
Jehof
A: 

Thanks brother. You cleared my concept on using UserControls. This was really helpful. Thanks again.

Samiul