4

我在 winfrom 中有 100 个复选框。他们的名字是连续的,如 checkbox1、checkbox2 等。我的 winform 中有一个提交按钮。单击提交按钮后,它会检查,如果选中了复选框,则更新某个值,否则更新另一个值。我必须选中 100 复选框。所以我必须遍历 100 复选框来检查复选框是否被选中。

我知道如何选中复选框

private void sumit_button_Click(object sender, EventArgs e)
{
     if (checkbox1.Checked)
     { 
        //  update 
     }
     else
     {  
        // update another  
     }

     if (checkbox2.Checked)
     {  
        //  update    
     }
     else
     {   
        // update another  
     }

     ......................and so on

} 

但是我怎样才能为 100 个复选框做到这一点???

4

6 回答 6

8
foreach (var control in this.Controls) // I guess this is your form
            {
                if (control is CheckBox)
                {
                    if (((CheckBox)control).Checked)
                    {
                        //update
                    }
                    else
                    {
                        //update another
                    }
                }
            }
于 2013-09-13T05:15:09.700 回答
5
foreach (var ctrl in panel.Controls) {
    if (ctrl is CheckBox && ((CheckBox)ctrl).IsChecked) {
        //Do Something
    }
}
于 2013-09-13T05:10:13.567 回答
2
foreach (var box in this.Controls.OfType<CheckBox>())
{
    if (box.Checked)
    {
        //...
    }
    else
    {
        //...
    }
}
于 2013-09-13T05:15:35.473 回答
2

有 LINQ 方法OfType。为什么不使用它来摆脱手动类型测试和铸造?

foreach (var ctrl in panel.Controls.OfType<CheckBox>().Where(x => x.IsChecked)
{
    // ....
}
于 2013-09-13T05:17:06.680 回答
1
    foreach (Control childc in Page.Controls)
    {

            if (childc is CheckBox)
            {
                CheckBox chk = (CheckBox)childc;
                //do your operation

            }

    }
于 2013-09-13T05:14:51.760 回答
0

This is the write answer for this................

c#

           string movie="";
           if (checkBox1.Checked == true)
            {
                movie=movie+checkBox1.Text + ",";
            }
            if (checkBox2.Checked == true)
            {
                movie=movie+checkBox2.Text + ",";
            }
            if (checkBox3.Checked == true)
            {
                movie=movie+checkBox3.Text + ",";
            }

            if (checkBox4.Checked == true)
            {
                movie = movie + checkBox4.Text + ",";
            }
            if (checkBox5.Checked == true)
            {
                movie = movie + checkBox5.Text + ",";
            }
            if (checkBox6.Checked == true)
            {
                movie = movie + checkBox6.Text + ",";
            }
          row["EnquiryFor"] = movie.ToString();

where row is a object of DataRow and EnquiryFor is the name of sql table column....

于 2014-08-22T09:41:07.987 回答