1

I want to attach an event to a button clicked generated at runtime. Till this point I've wrote the code, but can't pass the button's ID to the method. Here is my code

This code does not through any error, another problem is after the click event the controls get washed away. How to prevent this ?

protected void Button1_Click(object sender, EventArgs e)
   {
     int i = int.Parse(TextBox1.Text);
     for (int x = 1; x <= i; x++)
     {
       Button b = new Button();
       b.ID = "btn_" + x.ToString();
       b.Text = "btn_" + x.ToString();
       b.Click += new System.EventHandler(myEventHandler);
       pnlHolder.Controls.Add(b);
     }
   }

 private void myEventHandler(object sender, EventArgs e)
 {
   txtMain.Text = sender.ToString(); // I want to know which button was pressed
 }

2 Answers 2

2

try,

txtMain.Text = (sender as Button).Name;

or

txtMain.Text = (sender as Button).Text;
Sign up to request clarification or add additional context in comments.

1 Comment

Sender as button Just loved it (: +1
2

Try this

 private void myEventHandler(object sender, EventArgs e)
 {
   Button b = (Button) sender;
   txtMain.Text = b.ID;
   //
   txtMain.Text = b.Text;

   if(b.ID == "button1")
     doThis();
   else if(b.ID == "button2")
     doThat();
 }

2 Comments

Thanks, +1, btw can you help me with the another problem ? [controls removed after postback]
Asp.net is not like window forms. Controls state are lost at postback. That's why ASP.Net uses ViewState to remember controls you add through design or markup. You'll need to make your buttons as part of ViewState or recreate them everytime the page refreshes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.