0

我的winform中有多个组框,将根据树视图选择显示,我只想在所有组中使用一个按钮,我必须根据树视图选择调用唯一方法,怎么做?

4

1 回答 1

1

要根据您选择的 treeView 节点执行某些操作,您可以在 TreeView 控件的 AfterSelect 事件上执行此操作(假设您有 1 个 TreeView、4 个 GroupBox 和一个名为button1的按钮):

private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //Get current selected node
            TreeNode treenode = treeView1.SelectedNode;

            //Position the button so it will be visible, change according needs
            button1.Location = new Point(20, 20);

            //I'm making the selection using "Text" property
            switch (treenode.Text)
            {
                case "1":
                    changeVisible(groupBox1); //Hide all GroupBoxes excep groupBox1
                    groupBox1.Controls.Add(button1);//Add the button1 to GroupBox1 Controls property

                    //You can execute a specific ethod for this case here.
                    //DoSomethingForTreeNode1();

                    break;
                case "2":
                    changeVisible(groupBox2);
                    groupBox2.Controls.Add(button1);
                    break;
                case "3":
                    changeVisible(groupBox3);
                    groupBox3.Controls.Add(button1);
                    break;
                case "4":
                    changeVisible(groupBox4);
                    groupBox4.Controls.Add(button1);
                    break;
            }
        }


        //The only purpouse of this method is to hide all but the desired GroupBox control
        private void changeVisible(GroupBox groupBox)
        {
            //Loop across all Controls in the current Form
            foreach (Control c in this.Controls)
            {
                if(c.GetType() == typeof(GroupBox))
                {
                    if(c.Equals(groupBox))
                    {
                        c.Visible = true;

                    }
                    else
                    {
                        c.Visible = false;
                    }

                }

            }
        }

希望有帮助,

于 2013-02-26T19:37:04.303 回答