简体   繁体   中英

Pass dynamic button id to click event

I need some help with the following:

                //exampleList has 3 rows

                int count = 1;
                foreach (var item in exampleList)
                {
                Button btnExample = new Button();
                btnExample.ID = "btnExample" + count.ToString();
                btnExample.Text = "example";
                btnExample.Click += new System.EventHandler(btnExample_Click);
                count++;
                }

This piece of code will result in 3 buttons. All 3 buttons have the same event (btnExmple_Click). Those 3 fields have the following id's after running this code:

  • btnExample1
  • btnExample2
  • btnExample3

Now, when I click either one of those buttons, I need to redirect to another page and pass the id of the button. So, if I click the second button I want to pass btnExample2 with it. My question, can I do this in ASP.NET itself without the use of JS/Jquery? And if this is possible, how do I do that?

In your button handler :

protected void btnExample_Click(object sender, EventArgs e) {
   Button btn = (Button) sender;

   string id = btn.ID;

   //redirect page ...
}

Convert the sender object to be of type Button and then get the ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM