Dynamic Web Server Control

S

Surjit Madiwalar

Hi,

I have added dynamically 5 buttons to the panel.

How do i know which button clicked....suppose i click on add3 button how do
i trap that event....

The code is below:

// numShift is dynamic(range 3-12)
int numShift = 5;
for (int i=1; i<=numShift; i++)
{

Button buttonAdd = new Button();

buttonAdd.Text = "Add";

buttonAdd.ID = "ShiftAddButton" + i.ToString();

Panel1.Controls.Add(buttonAdd);

Panel1.Controls.Add(new LiteralControl("<br>"));

}

Your help is much appreciated.

Rgds,
Surjit
 
J

John Saunders

Surjit Madiwalar said:
Hi,

I have added dynamically 5 buttons to the panel.

How do i know which button clicked....suppose i click on add3 button how
do
i trap that event....

The code is below:

// numShift is dynamic(range 3-12)
int numShift = 5;
for (int i=1; i<=numShift; i++)
{

Button buttonAdd = new Button();

buttonAdd.Text = "Add";

buttonAdd.ID = "ShiftAddButton" + i.ToString();

buttonAdd.Click += new EventHandler(Button_Click);
Panel1.Controls.Add(buttonAdd);

Panel1.Controls.Add(new LiteralControl("<br>"));

}

private void Button_Click(object sender, EventArgs e)
{
Button sendingButton = (Button) sender;
// sendingButton.ID is the ID, in case you need that
}

John Saunders
 
R

Robert Koritnik

The code John suggested is ok since it connects an event with a handler,
but:

- since you are adding your controls dynamicly, make shure you recreate them
on the postback as late as in page Load event or your event won't fire.

- maybe you should consider using Command event instead of Click. Button
class has a property CommandArgument, which you can use for very varius
things. Maybe something should be written to the user when he clicks a
button. You could put there the string, so your handler would be VERY
simple. Or maybe it does something else and you could put in something you
could use without checking which button was clicked as Jon suggested. You
don't mind that, you just use CommandArgument and do the apropriate thing.
There's also a CommandName property if one string is not enough for the job.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top