Search code examples
c#formsdelegatesuser-controlstreeview

Updating a treeview from other usercontrol using delegate in C#


In a main form I have a treeview control where each node calls a different user control in a panel present in the main form. My problem is that one of these user controls is responsible to add/delete/update nodes of the treeview in the main form.

I have tried to do it using delegates it is not working.

In the main form I have a method like this:

public void UpDateTreeView()
{
    //load xml file that contain my nodes
    //do something

    myTreeView.Refresh();
}

In the User Control I'm trying it:

delegate void UpDatingMyTreeView();

private void buttonUpDate_Click(object sender, EventArgs e)
{
    //update the xml file with a new node
    //do something...

    frm_MainForm frm = new frm_MainForm frm();
    UpDatingMyTreeView updTrv = new UpDatingMyTreeView(frm.UpDateTreeView);
    updTrv();
}

I have never used delegates and it's not working. I'm using windows form application.


Solution

  • The solution starts when you can get the main form of the Uzur Control. We use the following method:

    yourUserControl.FindForm(); or this.FindForm();
    

    Then we do the next projection to get the Main form of Instance .

    private void buttonUpDate_Click(object sender, EventArgs e)
        {
          ((MainForm)this.FindForm()).UpDateTreeView();
        }
    

    UpDateTreeView() is public Method in MainForm .