从组合框选定项目中筛选树视图

时间:2012-07-01 11:27:56

标签: c# winforms treeview

树视图加载了来自DB的一些数据。我想过滤所选组合框项目的树视图。有谁告诉我如何执行此操作?

 public SelectorDataTreeView()
        {            
            InitializeComponent();

            button1.FlatStyle = FlatStyle.Flat;

            comboBox1.Items.Add("HP");
            comboBox1.Items.Add("DELL");
            comboBox1.Items.Add("Cam");

        }






        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           String s = comboBox1.SelectedItem.ToString();
           ExpandAll(MyTreeView.Nodes);
        }




        //TreeKey Finder
        private TreeNode[] FindNode(String searchKey)
        {

            return MyTreeView.Nodes.Find(searchKey, true);

        }
}

2 个答案:

答案 0 :(得分:1)

private void Form4_Load(object sender, EventArgs e)
    {
        treeView1.Nodes.Add("LaptopsNodeKey", "Laptop");
        treeView1.Nodes.Add("CellPhonesNodeKey", "Phones");
        treeView1.Nodes.Find("LaptopsNodeKey", true)[0].Nodes.Add("DellTM", "Dell");
        treeView1.Nodes.Find("LaptopsNodeKey", true)[0].Nodes.Add("SonyTM", "Sony");
        treeView1.Nodes.Find("CellPhonesNodeKey", true)[0].Nodes.Add("HTCTM", "HTC");
        treeView1.Nodes.Find("CellPhonesNodeKey", true)[0].Nodes.Add("NokiaTM", "Nokia");

        comboBox1.Items.Add("LaptopsNodeKey");
        comboBox1.Items.Add("CellPhonesNodeKey");

        comboBox2.Items.Add("Laptop");
        comboBox2.Items.Add("Phones");
    }

    //This works because you Loaded ComboBox1 with Name property of Nodes
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        treeView1.CollapseAll();
        treeView1.SelectedNode = treeView1.Nodes.Find(comboBox1.Text, true)[0];
        treeView1.SelectedNode.Expand();
    }

    //This doesn't work, because you Loaded ComboBox2 with Text property of Nodes
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
    {
        treeView1.CollapseAll();
        treeView1.SelectedNode = treeView1.Nodes.Find(comboBox1.Text, true)[0];
        treeView1.SelectedNode.Expand();
    }

答案 1 :(得分:1)

啊哈,这是你的错:
String s = comboBox1.SelectedItem.ToString();
你应该用这个:
    String s = comboBox1.Text;
它正在发挥作用。
并且您还应该搜索节点Name属性而不是Text属性 获得s之后,您需要像使用它一样使用它 treeView1.SelectedNode = treeView1.Nodes.Find("WantedNodesName", true)[0]; treeView1.SelectedNode.Expand();