简体   繁体   中英

How to show a display value for selected node in treeview in C#?

I am trying to create a treeview which pulls info from a sql database. I want the text to be the name field but when you double click the name i want it to display the id field. I have look and looked but cant find any info on this?

Code tried (Added from OP's comment):

   foreach (DataRow dr in Db.Table("Employee").Rows) 
   { 
      treeView1.Nodes.Add(
             new TreeNode(dr["Name"].ToString(),
             new TreeNode[] {new TreeNode(dr["EEID"].ToString())}));
   } 
      var node = treeView1.SelectedNode.Nodes[0].Text; 
      MessageBox.Show(string.Format("You selected: {0}", node));

When you create new nodes for a TreeView you can specify a text value and a key value, like so:

TreeView tv = new TreeView();
tv.Nodes.Add(key, text); //where key is your database id value, and text the display 

Then you'd simply return the key of the clicked node. Is this what you want?

EDIT: This is what happens when you speak from memory... this is wrong . 'key' is not a hidden key value, like an ID, 'key' is the name of the tree node. Please hold while I give you a proper solution.

** EDIT2 (SOLVED) ** : You can also use the Name property. Like this:

tView.Nodes.Add("Id_0001", "Mr. Dexter");

then you could retrieve the values of that node with something like this:

    private void tvView_AfterSelect(object sender, TreeViewEventArgs e)
    {
        TreeNode node = e.Node;
        MessageBox.Show(node.Name + "\n" + node.Text);
    }

which would yield the results: "Id_0001" and "Mr. Dexter".

foreach (DataRow dr in Db.Table("Employee").Rows)
{ 
  TreeNode tn = new TreeNode(); 
  tn.Tag = dr["eeid"]; 
  tn.Text = dr["Name"].ToString(); 
  treeView1.Nodes.Add(tn); 
} 
private void treeView1_DoubleClick(object sender, EventArgs e) 
{ 
  MessageBox.Show(treeView1.SelectedNode.Tag.ToString()); 
}

you can use Mouse Click event. when you click on a particular node (assume it's not WPF cause then it's Items) you can get its Text from SelectedNode property.

 private void btnGetNodeValue_Click(object sender, EventArgs e)
        {
            string nodeVal=  treeView1.SelectedNode.Text;

        }

then you can pass this string value to database to retrieve your value,mix up with Select statement and WHERE clause so you can easily get it.

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