Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do i transfer variables from the function to the thread?

for some reason this code throws me an error

private void button1_Click(object sender, EventArgs e)
{
    treeView1.BeginUpdate();
    TreeNode labelnode = treeView1.Nodes[0].Nodes.Add("Label" + labelnum.ToString());
    treeView1.EndUpdate();

    //create id
    string id = "1";

    Thread thread = new Thread(new ThreadStart(Worker(labelnode, id))); // it errors out here
    thread.Start();
}

private void Worker(TreeNode labelnode, string id)
{ 
    while (true)
    {
        Thread.Sleep(50);
        if (labelnode.IsSelected == true)
        {
            showProperties("label", id);
        }
    }
}

what i was trying to do here is show properties when labelnode was selected. would be glad and thankful if someone helped me

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems that what the code is trying to do is check whether a node is selected. The proper way to do this is to use the TreeView.AfterSelect event. Using a thread like this will peg a CPU core at 100% doing nothing.

private void TreeView1_AfterSelect(System.Object sender, 
    System.Windows.Forms.TreeViewEventArgs e)
{
    if (e.Node==treeView1.Nodes[0]) //Or whatever condition you want
    {
        showProperties("label", e.Node.Tag);
    }
}

In Windows Forms almost all controls have a Tag property that can be used to store anything the application wants. You can store the ID value in the new node’s tag :

TreeNode labelnode = treeView1.Nodes[0].Nodes.Add("Label" + labelnum.ToString());
labelNode.Tag="1";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading