[英]Dynamic adding of checkboxes in asp.net using c#?
I am trying to add two sets of checkboxes
in my asp.net
project. 我试图在我的
asp.net
项目中添加两组checkboxes
。 There I am doing this: 我在这里这样做:
on page load: 页面加载:
public static CheckBox[] chck = new CheckBox[100];
public static CheckBox[] chckbx = new CheckBox[100];
and i have a functions: 我有一个功能:
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 />"));
}
}
and i am calling this function here: 我在这里调用此函数:
protected void ddluserwebser_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddluserwebser.SelectedItem.Text == "Custom")
{
generatecheckbox1();
}
}
The problem is i am getting an error page like this: 问题是我收到这样的错误页面:
its saying this: 它说:
Multiple controls with the same ID 'System.Web.UI.WebControls.CheckBox[]0' were found. FindControl requires that controls have unique IDs.
But I am assigning different ids..
what should i do? 但是我分配了不同的
ids..
我该怎么办?
The problem is that you're creating two checkboxes in one loop iteration with the same id. 问题是您要在一个具有相同ID的循环迭代中创建两个复选框。 That's not allowed in ASP.NET when they are in the same
NamingContainer
( Panel
doesn't implement INamingContainer
). 当它们位于同一
NamingContainer
(在Panel
中未实现INamingContainer
),这在ASP.NET中是不允许的。
So change it to(note the string.Format
part): 因此将其更改为(注意
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 />"));
}
You also have used the CheckBox[]
to build your ID 您还使用了
CheckBox[]
来构建您的ID
chckbx + Convert.ToString(i);
That works seemingly since Type
+ string
= name of the type + string but looks like: 这似乎可行,因为
Type
+ string
= Type
名称+字符串,但看起来像:
"System.Windows.Forms.CheckBox[]99"
So just use the code above 所以只要使用上面的代码
string.Format("chk_1_{0}", i);
don't chck here chck[i].ID = chck + Convert.ToString(i);
不要在这里
chck[i].ID = chck + Convert.ToString(i);
needs to be chck[i].ID = "chck" + Convert.ToString(i);
需要为
chck[i].ID = "chck" + Convert.ToString(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.