简体   繁体   中英

How can I get a treeview from another form?

I am trying to implement a search function in a treeview.
So, I want to get the value to be retrieved in a new form. But my code error with this message. System.NullReferenceException

Form1.cs

public TreeView TreeView1
{
    get { return treeView1; }
    set { this.treeView1 = value; }
}

Form2.cs

public void btnClick(object sender, EventArgs e)
{
    Form1 form1 = new Form1();
    label1.Text = form1.TreeView1.SelectedNode.Text;
}

Try this:

    Form1 form1 = new Form1();

    form1.TreeView1.AfterSelect += (sender1, e1) =>            
        label1.Text = e1.Node?.Text ?? string.Empty;
        
    form1.Show();

You need create and show the form. Then, we manage AfterSelect event of TreeView of the new created form to set the Label text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM