tags:

views:

97

answers:

2

I am adding controls dynamically during runtime using a conrolplace holder. i want to add buttons and handle their event. they will do the same thing but with different parameter. here is a sample of the code:

while (dataReader.Read())
{
      Button edit = new Button();

      PlaceHolderQuestions.Controls.Add(edit);
}

i need to handle the event of the buttons. Thanks

A: 

You can just create a method, then add:

edit.Click += YourMethodName;

As long as the same button is created on postback before the eventhandler is raised, the event will fire.

ck
thx man. but where shall i write this line? edit.Click += new EventHander(EditButton_Click); under the declaration of the button
Ahmad Farid
+4  A: 

A couple of things:

Firstly you need to make sure the new Controls are added in the Page.OnInit event, so that they are added before the raised events are processed.

They also need to be added again on a postback!

They also need to have a unique ID set.

Finally you can handle the event just like you would in any C# app:

edit.Click += new EventHander(EditButton_Click);

and later in the code:

protected void EditButton_Click(object sender, EventArgs e)
{
  // Do Something
}
samjudson
+1 for "make sure the new Controls are added in the Page.OnInit event"...a lot of people make this wrong
Juri
same as Juri ... +1 for OnInit ... common mistakes that can be frustrating to debug
Chris Nicol
The first time I did this it was not setting the ID that really got me for ages.
samjudson
thx man. but where shall i write this line? edit.Click += new EventHander(EditButton_Click);under the declaration of the button?
Ahmad Farid
Yes, right after the Button edit = new Button() line.
samjudson
hey it works pretty well thanks!!sorry but i have another question, like i told u, i have many buttons like that so i want to differentiate between them; to know which one is pressed, how can i do that?
Ahmad Farid
Put "Button thisButton = (Button)sender;" in the event handler.
samjudson