Saturday, March 12, 2011

Attaching click events to dynamically created asp.net buttons


Creating a button

we can always create buttons dynamically using asp.net.How about attaching event to dynamically created event?Well its not a very difficult the .NET APIs provide a provision to attach a event to the dynamically created buttons
The traditional way of creating buttons dynamically is
Button btn = new Button
{
ID = "myButton",
Text = "My Button"
};
and the way to attach event to it

btn.Click += new EventHandler(btn_Click); 
The above declaration should be made in OnInit(EventArgs e)
Now what if we need to create 10 buttons based on the entries in database and we need to attach click event to all the 10 buttons
There are two ways to achieve the same.
1. Creating a delegate
2. Using reflection apis to attach event to event handler list

Creating a Delegate

First Lets create a button
Button btn = new Button {
ID = "myButton",
Text = "My Button"
};
we will store the event name for our button in a string
string eventName = "btn_Click"; 
Define a temporary delegate as below

Delegate temp = Delegate.CreateDelegate(typeof(EventHandler), this, eventName);
The above line of code will create a delegate for our button
To attach the above created delegate with the button we will simply write
 btn.Click += (EventHandler)temp;

Using Reflection

This way is little advanced first we need to create a delegate first and then we need to attach it to the event handler list

Delegate temp = Delegate.CreateDelegate(typeof(EventHandler), this, eventName);FieldInfo f1 = typeof(Button).GetField("EventClick", BindingFlags.Static 
BindingFlags.NonPublic);
Get the button object
object obj = f1.GetValue(btn);
PropertyInfo pi = typeof(Button).GetProperty("Events", BindingFlags.NonPublic 
BindingFlags.Instance);
EventHandlerList list = (EventHandlerList)pi.GetValue(btn, null);
Attach a created delegate to event handler list
list.AddHandler(obj, temp);
Now we are good to go to test our newly created dynamic buttons