如何通过按按钮输入的文本来搜索此树形视图中的特定节点?

时间:2019-04-26 10:22:20

标签: c# treeview

我有一个简单的代码,用于使用添加,删除和编辑按钮创建树结构。我想通过文本框(textBox1)和按钮press(button4)从添加的节点中搜索特定的节点,但是我似乎无法使其工作。有什么建议吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
     public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {

        TreeNode node = new TreeNode(textBox1.Text);



        try
        {
            treeView1.SelectedNode.Nodes.Add(node);
        }
        catch (Exception)
        {
            treeView1.Nodes.Add(node);
        }
    }

    private void Button2_Click(object sender, EventArgs e)
    {
        treeView1.SelectedNode.Text = textBox1.Text;
    }

    private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
        textBox1.Text = treeView1.SelectedNode.Text;    
    }

    private void Button3_Click(object sender, EventArgs e)
    {
        treeView1.SelectedNode.Remove();       
    }

    private void Button4_Click(object sender, EventArgs e)
    {

    }
}

}

1 个答案:

答案 0 :(得分:0)

只需使用像这样的linq查询:

TreeNode[] treeNodes = treeView1.Nodes.Cast<TreeNode>() .Where(r => r.Text == textBox1.Text).ToArray();