Reputation: 699
I am trying to add two sets of checkboxes
in my asp.net
project. 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?
Upvotes: 0
Views: 5908
Reputation: 460118
The problem is that you're creating two checkboxes in one loop iteration with the same id. That's not allowed in ASP.NET when they are in the same NamingContainer
(Panel
doesn't implement INamingContainer
).
So change it to(note the string.Format
part):
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
chckbx + Convert.ToString(i);
That works seemingly since Type
+ string
= name of the type + string but looks like:
"System.Windows.Forms.CheckBox[]99"
So just use the code above
string.Format("chk_1_{0}", i);
Upvotes: 3
Reputation: 3453
don't chck here chck[i].ID = chck + Convert.ToString(i);
needs to be
chck[i].ID = "chck" + Convert.ToString(i);
Upvotes: 0