带变量的复选框的检查状态.复选框(我).检查

本文关键字:复选框 检查 状态 变量 | 更新日期: 2023-09-27 18:14:10

我有30个复选框在我的web表单,我想存储复选框的bool数组的状态。现在,由于asp.net不接受使用带有变量"i"的复选框的"已选中"状态,问题是我不知道如何执行代码!

我想要这样的东西:

bool[] array = new bool[30];
for (int i = 0; i < 30; i++)
   {
      array[i] = CheckBox(i).Checked ;
   }
当你运行上面的代码时,你会得到这个错误:
Compilation Error 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 
Compiler Error Message: CS0118: 'System.Web.UI.WebControls.CheckBox' is a 'type' but is used like a 'variable'
Source Error:
Line 109:        for (int i = 0; i < 30; i++)
Line 110:        {
Line 111:            array[i] = CheckBox(i).Checked;
Line 112:        }
Line 113:  

我很想知道我如何使用一个变量的复选框的id,如:

i = 15;
CheckBox(i).Checked

代替:

CheckBox15.Checked

ASP.net 4和c#谢谢大家。

带变量的复选框的检查状态.复选框(我).检查

try this:

bool[] array = new bool[30];
for (int i = 0; i < 30; i++)
{
   array[i] = ((CheckBox)Page.FindControl("CheckBox" + i.ToString)).Checked;
}

更新:

我刚刚创建了一个新项目,只是为了测试代码是否工作,它工作了。真的。: |

<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="CheckBox1" runat="server" />
        <asp:CheckBox ID="CheckBox2" runat="server" />
        <asp:CheckBox ID="CheckBox3" runat="server" />
        <asp:CheckBox ID="CheckBox4" runat="server" />
        <asp:CheckBox ID="CheckBox5" runat="server" />
        <asp:CheckBox ID="CheckBox6" runat="server" />
        <asp:CheckBox ID="CheckBox7" runat="server" />
        <asp:CheckBox ID="CheckBox8" runat="server" />
        <asp:CheckBox ID="CheckBox9" runat="server" />
        <asp:CheckBox ID="CheckBox10" runat="server" />
    </div>
    </form>
</body>

后台代码:

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bool[] array = new bool[10];
        for (int i = 1; i <= 10; i++)
        {
            array[i] = ((CheckBox)Page.FindControl("CheckBox" + i.ToString())).Checked;
        }
    }
}