简体   繁体   中英

Display text in treeview when text in listBox is selected C#

I am working on a window form application which has a list box and a treeview. In my listBox, I have 3 items and they are student, teacher, and staff. I don't have anything in my treeview yet. In my treeview, I want the text changed according to what I select in my listBox. Are there way to do this? I tried to put treeView1.Nodes.Add("Class") in my list box method which see if it is equals to student. But all it does is to add the node class to my treeview everytime I click student. I am not sure how to fix this. Help will be appreciated, thanks.

list box method

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            foreach (var listItem in roleListBox.SelectedItems)
            {
                if (String.Equals(listItem.ToString(), "teacher", StringComparison.CurrentCultureIgnoreCase)) 
                {
                    //Display Class
                   treeView1.Nodes.Add("Class");
                }

                if(String.Equals(listItem.ToString(), "student", StringComparison.CurrentCultureIgnoreCase))
                {
                  //Display Salary
                  treeView1.Nodes.Add("Salary");
                }

                if(String.Equals(listItem.ToString(), "staff", StringComparison.CurrentCultureIgnoreCase))
                {
                    //Display Department
                }
            }
        }

treeview method

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {



        }

Before adding node, Check whether it is already added and set the key of the node.

if (String.Equals(listItem.ToString(), "teacher", StringComparison.CurrentCultureIgnoreCase)) 
{ 
    if(treeView1.Nodes.ContainsKey("Class")==false)
    {
       //Display Class
       treeView1.Nodes.Add("Class","Class");
    }
}

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