[英]Dynamic adding of checkboxes in asp.net using c#?
我试图在我的asp.net
项目中添加两组checkboxes
。 我在这里这样做:
页面加载:
public static CheckBox[] chck = new CheckBox[100];
public static CheckBox[] chckbx = new CheckBox[100];
我有一个功能:
public void generatecheckbox1()
{
for (int i = 0; i < 99; i++)
{
chck[i] = new CheckBox();
chck[i].ID = chck + Convert.ToString(i);
chck[i].Text = chck + Convert.ToString(i);
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
chckbx[i] = new CheckBox();
chckbx[i].ID = chckbx + Convert.ToString(i);
chckbx[i].Text = chckbx + Convert.ToString(i);
pnlcom2.Controls.Add(chckbx[i]);
pnlcom2.Controls.Add(new LiteralControl("<br />"));
}
}
我在这里调用此函数:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
问题是我收到这样的错误页面:
它说:
Multiple controls with the same ID 'System.Web.UI.WebControls.CheckBox[]0' were found. FindControl requires that controls have unique IDs.
但是我分配了不同的ids..
我该怎么办?
问题是您要在一个具有相同ID的循环迭代中创建两个复选框。 当它们位于同一NamingContainer
(在Panel
中未实现INamingContainer
),这在ASP.NET中是不允许的。
因此将其更改为(注意string.Format
部分):
for (int i = 0; i < 99; i++)
{
chck[i] = new CheckBox();
chck[i].ID = string.Format("chk_1_{0}", i);
chck[i].Text = chck + Convert.ToString(i);
pnlcom1.Controls.Add(chck[i]);
pnlcom1.Controls.Add(new LiteralControl("<br />"));
chckbx[i] = new CheckBox();
chck[i].ID = string.Format("chk_2_{0}", i);
chckbx[i].Text = chckbx + Convert.ToString(i);
pnlcom2.Controls.Add(chckbx[i]);
pnlcom2.Controls.Add(new LiteralControl("<br />"));
}
您还使用了CheckBox[]
来构建您的ID
chckbx + Convert.ToString(i);
这似乎可行,因为Type
+ string
= Type
名称+字符串,但看起来像:
"System.Windows.Forms.CheckBox[]99"
所以只要使用上面的代码
string.Format("chk_1_{0}", i);
不要在这里chck[i].ID = chck + Convert.ToString(i);
需要为chck[i].ID = "chck" + Convert.ToString(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.