Home > Net >  How to reassign a TreeView object and have the UI reflect that change
How to reassign a TreeView object and have the UI reflect that change

Time:08-26

I have a single TreeView in my WinForms UI that I want to share with multiple datasets depending on the checked state of a series of radio buttons.

What I would like to do is have a series of hidden TreeView objects in code that I can just assign to the visible TreeView and tell the UI to refresh itself and display the newly assigned TreeView. Unfortunately, the display TreeView, never displays any data unless I manually add nodes to it. I don't want to have to constantly copy nodes in and out of the treeview, keeping track of checked states etc every time I swap views. Is there an easy way to do what I'm wanting?

TreeView visibleView = new TreeView(); //This is the tv exposed in the UI.
TreeView view1 = BuildTreeView(bDoSomething); //This method adds nodes to a treeview and returns it
TreeView view2 = BuildTreeView(bDoSomethingElse); //Similar to above, just slightly different.

//Depending on checked state, display different TreeView.
if(combobox1.Checked)
     //This is a reference assignment. 
     //Why won't the visibleView just take on the form of view1?
     visibleView = view1; 
else
     visibleView = view2;

//Tell UI to display the newly assigned view.
visibleView.Refresh();

CodePudding user response:

Show and hide your different TreeView instances as approriate:

TreeView view1 = BuildTreeView(bDoSomething); 
TreeView view2 = BuildTreeView(bDoSomethingElse);

//Depending on checked state, display different TreeView.
if(combobox1.Checked)
{
     view1.Show();
     view2.Hide();
} 
else
{
     view1.Hide();
     view2.Show();
}

CodePudding user response:

Ok, thanks to Neils suggestion I dove back into the code and discovered my error. The reference assignment works fine. The new treeview wasn't being displayed because it hadn't been added to the controls array for the panel in which it was supposed to be displayed. The following code works for me now.

this.panel1.Controls.Remove(visibleTreeView);
visibleTreeView = view1;
this.panel1.Controls.Add(visibleTreeView);
visibleTreeView.Dock = DockStyle.Fill;
visibleTreeView.Refresh();
  • Related