Event handlers and dynamically created controls

G

Guest

I have created a method that dynamically creates a single button control (as
a proof-of-concept, I would like to be able to create multiple buttons). I
set properties on this control including an event handler for the click
event. The problem is that when I click the button on the page and view the
locals window in debug mode, I don't see any information on the button
control.

Say, I want to create a variable number of buttons based on some user input,
these buttons would be created with an ID=Btn1, ID=Btn2, etc. And say that I
want to have all of these buttons call the same event handler when clicked.
In this event handler I would like to be able to interrogate the button
object that raised the event to determine which id number it is.
Here is the code:

private void createControl()
{
// Create and configure a single button control.
Button btn = new Button();
btn.ID = "btn1";
btn.Width = Unit.Pixel(75);
btn.Height = Unit.Pixel(25);
btn.Text = "Click Me";
EventArgs e = new EventArgs();
btn.Click += new EventHandler(this.btn_Click);
btn.Style.Add(HtmlTextWriterStyle.Left,"100px");
btn.Style.Add(HtmlTextWriterStyle.Top,"100px");
btn.Style.Add(HtmlTextWriterStyle.Position,"absolute");

// Add this control to the form.
this.form1.Controls.Add(btn);
}

private void btn_Click(object sender, System.EventArgs e)
{
Response.Write("Hello from dynamic control: ");
}

Any ideas, or comments would be greatly appreciated!
Thanks,
- Mike
 
S

senfo

Mike said:
In this event handler I would like to be able to interrogate the button
object that raised the event to determine which id number it is.
Here is the code:
private void btn_Click(object sender, System.EventArgs e)
{
Response.Write("Hello from dynamic control: ");
}

private void btn_Click(object sender, System.EventArgs e)
{
Button btn;

if ((btn = sender as Button) != null)
{
Response.Write("Hell from dynamic control: " + btn.ID);
}
}

Hope that helps,
 
G

Guest

Sean,
Thanks, that worked perfectly!
- Mike

senfo said:
private void btn_Click(object sender, System.EventArgs e)
{
Button btn;

if ((btn = sender as Button) != null)
{
Response.Write("Hell from dynamic control: " + btn.ID);
}
}

Hope that helps,
 

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,989
Messages
2,570,207
Members
46,782
Latest member
ThomasGex

Latest Threads

Top