【问题标题】:Using a Treeview to display information使用 Treeview 显示信息
【发布时间】:2016-03-24 09:07:21
【问题描述】:

我有一个treeview,其中包含国家/地区列表,我还有一个textbox,其中包含有关每个国家/地区的描述如何根据单击的节点更改描述中的文本。

【问题讨论】:

    标签: c# winforms treeview


    【解决方案1】:

    您可以订阅TreeViewAfterSelect事件:

    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;
        }
    }
    

    我通常将TreeNodeTag 属性设置为对应的模型实例。因此,如果您有这样的 Country 类:

    public class Country
    {
        public string Name { get; set; }
        public string Description { get; set; }
    }
    

    我会像这样添加TreeNodes

    Country country = new Country { Name = "SomeCountry", Description = "description" };
    TreeNode nextNode = new TreeNode(country.Name);
    nextNode.Tag = country;
    parentNode.Nodes.Add(nextNode);
    

    您的 AfterSelect 处理程序可能如下所示:

        private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            textBox1.Text = (treeView1.SelectedNode?.Tag as Country)?.Description ?? string.Empty;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2010-10-16
      相关资源
      最近更新 更多