How to use TreeView.AfterSelect and TreeView.DrawNode methods?

.net, c#, treeview, winforms

Solution

If your TreeView controls are on different forms, they either need to reference each other through a form property or an event so that the controls can talk to each other.

The other thing I see is that you probably shouldn't be setting a property in a draw or paint event, which you are doing with `e.Node.Tag = myTreeView.SelectedNode.Text;` in the DrawNode event. The only thing you should be doing in the DrawNode event is drawing the node, very little else.

To make the reference, your costume form needs a variable and just pass it through the constructor, something like:

private MyForm mainForm;

private CostumeTreeView(MyForm mf) {
  InitializeComponents();
  mainForm = mf;
}

Now you can reference the TreeView control:

private void myCostumeTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) {
  ........
  e.Node.Tag = mainForm.myTreeView.SelectedNode.Text; 
}

Again, using the DrawNode event to set the tag of the nodes isn't necessary. You are creating a dependency on your GUI, which will make maintenance and debugging difficult in the future.

Problem

I have `MyForm.cs, MyForm.Designer.cs` files in my project, in `MyForm.Designer.cs` I did like this: ``` private System.Windows.Forms.TreeView myTreeView; this.myTreeView = new System.Windows.Forms.TreeView(); ......... this.myTreeView.AfterSelect += new TreeViewEventHandler(this.myTreeView_AfterSelect); ``` in `MyForm.cs` like this: ``` private void myTreeView_AfterSelect(object sender, TreeViewEventArgs e) { //........; } ``` also I have `CostumeTreeView` class in other files(`CostumeTreeView.cs` and `CostumeTreeView.Designer.cs`), in `CostumeTreeView.Designer.cs` I did like this: ``` private System.Windows.Forms.TreeView myCostumeTreeView this.myCostumeTreeView = new System.Windows.Forms.TreeView(); ........... this.myCostumeTreeView.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll; this.myCostumeTreeView.DrawNode += new DrawTreeNodeEventHandler(this.myCostumeTreeView_DrawNode); ``` in `CostumeTreeView.cs` : ``` private void myCostumeTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) { ........ //Here is the problem, myTreeView isn't seen here e.Node.Tag = myTreeView.SelectedNode.Text; } ``` I need when `myTreeView`'s node is selected, all tags in `myCostumeTreeView` is been changed using after select function (all methods are in one namespace)

Original source