讀取多個CheckBox控件

技術分享圖片

//方法1
private void button1_Click(object sender, EventArgs e)
        {
            //遍歷groupBox裏的所有控件:Comtrol
            foreach (Control c in groupBox3.Controls)     
            {//判斷當前Comtrol是不是Checkbox控件?
               if (c is CheckBox)
               {//是,轉換類型為Checkbox控件
                    CheckBox ck = c as CheckBox;
                //判斷Checkbox控件是不是checked?
                   if (ck.Checked)
                   {//是,取Text文本
                    this.groupBox3.Text += ShowChecked(ck);
                   }
               }
            }
         }
 private string ShowChecked(CheckBox ck) //返回string類型
        {   //字符串構造器
            StringBuilder sb = new StringBuilder();
            if (ck.Checked)
            {   //自動帶回車換行符
                sb.AppendLine(ck.Text);//沒選中返回空
            }
            return sb.ToString(); //返回字符串
        }        
//方法2
 private void button1_Click(object sender, EventArgs e)
        {
                        DealCheckboxes(groupBox3, groupBox3);
        }

        public void DealCheckboxes(Control container,Control contorlToDisplay)
        {
            contorlToDisplay.Text = "";
           foreach (Control c in container.Controls)
           {
             if (c is CheckBox)
             {
                 contorlToDisplay.Text += ShowChecked(c as CheckBox);
             }
           } 
        }
        private string ShowChecked(CheckBox ck) //返回string類型
        {   //字符串構造器
            StringBuilder sb = new StringBuilder();
            if (ck.Checked)
            {   //自動帶回車換行符
                sb.AppendLine(ck.Text);//沒選中返回空
            }
            return sb.ToString(); 
        }

讀取多個CheckBox控件選中的Text文本