我的网络表单中有30个复选框,我想将复选框的状态存储在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# 谢谢你们。
答案 0 :(得分:1)
试试这个:
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;
}
}
}