Reputation: 1119
I have a treeview
which has a list of countries, i also have a textbox
with a description about each country how can i change the text in the description depending on which node is clicked.
Upvotes: 0
Views: 213
Reputation: 43886
You can subscribe to the AfterSelect
event of your TreeView
:
public partial class Form1
{
private TreeView treeView1;
private TextBox textBox1;
// ... shortened example
public Form1()
{
InitializeComponent();
treeView1.AfterSelect += treeView1_AfterSelect;
//...
}
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string description = string.Empty;
TreeNode node = treeView1.SelectedNode;
if (node != null)
description = // determine the text from your country data
textBox1.Text = description;
}
}
I normally set the Tag
property of the TreeNode
to the corresponding model instance. So if you have a Country
class as this:
public class Country
{
public string Name { get; set; }
public string Description { get; set; }
}
I'd add TreeNodes
like this:
Country country = new Country { Name = "SomeCountry", Description = "description" };
TreeNode nextNode = new TreeNode(country.Name);
nextNode.Tag = country;
parentNode.Nodes.Add(nextNode);
And your AfterSelect
handler could look like this:
private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = (treeView1.SelectedNode?.Tag as Country)?.Description ?? string.Empty;
}
Upvotes: 1