1

This first section is in a loop. It creates the dynamic check boxes with no problems.

// All I am doing here is incrementing our session counter
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(this.chkDynamic_CheckedChanged);
Panel1.Controls.Add(chkDynamic);

My event handler is not wiring up for this. Strangly if I hard code the ID it does work, but only for one iteration of the loop because if we hard coded the IDs then we would run into 'multiple id errors'

protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
    if (chkDynamic.Checked)
        Response.Write( "you checked the checkbox");
    else if (!chkDynamic.Checked)
        Response.Write("checkbox is not checked");
}

1 Answer 1

3

You need to check sender in your event handler to know which checkbox sent the event:

protected void chkDynamic_CheckedChanged(object sender, EventArgs e)
{
    if (((CheckBox)sender).Checked)
        Response.Write( "you checked the checkbox");
    else 
        Response.Write("checkbox is not checked");
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain further? I have tried every combination of syntax and I can not get the above to work
I've literally copy / pasted your code and the events are not firing at all now. No errors, just not firing. I know this must be the correct route :(
Works great! One question. Do you know why it only works when I change string chk = "chk" + id.ToString(); to string chk = "chk"; Its not liking it when I append to the ID for somereason...
Without seeing more of your app, I cannot be sure. I do know that dynamically creating controls can wreak havoc with the postback mechanism if the controls aren't re-created at the correct time. For example, the meaning of the "CheckedChanged" event is that the Checked property changed since the last postback. But if the control doesn't exist on the next postback (since it is dynamic, you will need to re-create it every time), then the event won't fire. Since you use the session value to create your ID, on the next postback the checkboxes will all have different IDs. Make sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.