I have a very dynamic web app that is dynamically created controls at run-time.
Here is the first needed part of my code to solve my issue.
This is in a for loop, essentially it creates multiple checkbox’s with ID’s and event handlers.
// All I am doing here is incrementing our session counter so we can increment our ID
int id = Convert.ToInt32(Session["id"]);
id++;
Session["id"] = id;
// Now I create my checkbox
chkDynamic = new CheckBox();
chkDynamic.Text = "hey";
string chk = "chk" + id.ToString();
chkDynamic.ID = chk;
chkDynamic.CheckedChanged += new EventHandler(chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);
This next section is our custom even handler
protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write("you checked the checkbox :" + this.chkDynamic.ID);
else
Response.Write("checkbox is not checked");
}
The thing that strikes me as ODD. Is that this will work perfectly fine if I change:
string chk = "chk" + id.ToString();
To:
string chk = "chk";
But then of course we run into “multiple controls with the same ID”
My problem is getting this to work with unique ID’s! Another bit of ODD information that may help. If I take it out of a loop, and manually add a checkbox with a different ID it works as well. This is mind boggling 🙁
chkDynamic = new CheckBox();
chkDynamic.Text = "hey";
// string chk = "chk" + id.ToString();
chkDynamic.ID = "hey1";
chkDynamic.CheckedChanged += new EventHandler(chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);
chkDynamic = new CheckBox();
chkDynamic.Text = "hey";
// string chk = "chk" + id.ToString();
chkDynamic.ID = "hey2";
chkDynamic.CheckedChanged += new EventHandler(chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);
I have also debugged my program, and the values stored in the Session[“id”] are not null nor corrupt. Always holding value 0 and up!
Thanks for looking guys / gals. I’m really stuck on this!
PS – Sorry. There are no errors. The events just do not fire unless I hard code the ID’s.
Maybe you forget to reset the sesssion(“ID”), so when the page posts back the checkboxes are recreated with new ids. Since the checkbox-es are recreated on every postback, they need to have the same ID every time and if they don’t they are percepted as new controls and therefor the event handler is not called.