C#控件遍历(获取控件名)

时间:2022-01-12 11:24:35

C#中,遍历窗体上的控件,并显示在ListBox1中:

private void button1_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            GetControl(this.Controls);
        }

        private void GetControl(Control.ControlCollection ctc)
        {
            foreach (Control ct in ctc)
            {
                //调用AddControlInofToListBox方法获取控件信息
                AddControlInofToListBox(ct);
                //C#只遍历窗体的子控件,不遍历孙控件
                //当窗体上的控件有子控件时,需要用递归的方法遍历,才能全部列出窗体上的控件
                if (ct.HasChildren)
                {
                    GetControl(ct.Controls);
                }
            }
        }

        private void AddControlInofToListBox(Control ct)
        {
            switch (ct.GetType().Name)
            {
                //如果是ListBox、CheckBox、Button
                case "ListBox":
                case "GroupBox":
                case "Button":
                    listBox1.Items.Add("控件名:" + ct.Name);
                    break;


                //如果是CheckBox
                case "CheckBox":
                    if (((CheckBox)ct).Checked)
                    {
                        listBox1.Items.Add("控件名:" + ct.Name + ",是否选中:是");
                        //((CheckBox)ct).Checked = false;
                    }
                    else
                    {
                        listBox1.Items.Add("控件名:" + ct.Name + ",是否选中:否");
                        //((CheckBox)ct).Checked = true;
                    }
                    break;


                //如果是RadioButton
                case "RadioButton":
                    RadioButton rdb = (RadioButton)ct;
                    if (rdb.Checked)
                    {
                        listBox1.Items.Add("控件名:" + ct.Name + ",是否选中:是");
                        //rdb.Checked = false;
                    }
                    else
                    {
                        listBox1.Items.Add("控件名:" + ct.Name + ",是否选中:否");
                        //rdb.Checked = true;
                    }
                    break;


                //其它值
                default:
                    listBox1.Items.Add("控件名:" + ct.Name + ",值:" + ct.Text);
                    break;
            }
        }

        //遍历groupBox1控件的子控件

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            //可以共用上面的,遍历窗体控件的方法
            //只是参数由Controls改为groupBox1.Controls
            GetControl(groupBox1.Controls);
        }