Reputation: 4941
I have been getting some massive head aches working on a very dynamic app.
I am using a dynamic placeholder control from:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
This saves me a lot of hassle when trying to re-create dynamically created controls after a postback.
Has anyone else had any issues with attaching a event handler to checkbox control?
Here is my code for the dynamically created checkbox.
// Now I create my checkbox
chkDynamic = new CheckBox();
string chk = "chk";
// Add it to our dynamic control
chkDynamic.CheckedChanged += new EventHandler(chkDynamic_CheckedChanged);
chkDynamic.ID = chk;
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
chkDynamic.Text = "hey";
This works, but its like the event is not getting attached! Here is my event 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");
}
Now if I was to use a regular placeholder or a panel this works great.
Ex. Change this line:
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
to
Panel1.Controls.Add(chkDynamic);
And it works perfect.
Could someone please tell me, is this an issue with this control, or my coding?
There are no errors, the only thing that is happening that is unexpected is my event is not firing when I'm using the DynamicControlsPlaceholder.
Upvotes: 1
Views: 2791
Reputation: 954
Creating a delegate (anonymous method) did the job for me.
// Now I create my checkbox
chkDynamic = new CheckBox();
string chk = "chk";
// Add it to our dynamic control
chkDynamic.CheckedChanged += delegate (System.Object o, System.EventArgs e)
{
if (((CheckBox)sender).Checked)
Response.Write("you checked the checkbox :" + this.chkDynamic.ID);
else
Response.Write("checkbox is not checked");
};
chkDynamic.ID = chk;
DynamicControlsPlaceholder1.Controls.Add(chkDynamic);
chkDynamic.Text = "hey";
this will cause the code written in delegate to execute whenever dynamic control hits the action "CheckedChanged"
Upvotes: 1
Reputation: 6249
If you are adding dynamic controls, you MUST create/recreate the controls no later than OnInit()
. This is the point in the .NET page lifecycle where the viewstate and events are restored. If it is solely for the purpose of adding dynamic controls that you are using the dynamic placeholder control, then simply putting the control creation/recreation in OnInit()
will solve your problem. Give it a try and let me know your results.
Upvotes: 0
Reputation: 4941
Ok, so this works with one dynamically created control. But not with multiple...
Upvotes: 0