View Single Post
  #5 (permalink)  
Old May 24th, 2010, 04:04 AM
Imar's Avatar
Imar Imar is offline
Wrox Author
Points: 72,073, Level: 100
Points: 72,073, Level: 100 Points: 72,073, Level: 100 Points: 72,073, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,587 Times in 1,563 Posts
Default

First a little disclaimer: I completely agree with previous posters in that you probably don't need to find out which button was clicked in Page_Load. Instead, you should probably restructure your code so the buttons can handle whatever they need to handle, and Page_Load sets the stage for the buttons to do what they need to do.

Also, the solution I am posting here has issues on its own. Server IDs may change based on their location in the page hierarchy, you may rename your buttons and so on. It also defeats the idea of object orientation and uses techniques that ASP.NET was designed for to minimize.

That all said, you can simply read the Request.Form collection to see what which button caused the post back. Using myButton.UniqueID you get the name attribute used in the client HTML:

Code:
 
if (!string.IsNullOrEmpty(Request.Form[Button1.UniqueID]))
{
  Label1.Text = "Button 1 clicked";
}
if (!string.IsNullOrEmpty(Request.Form[Button2.UniqueID]))
{
  Label1.Text = "Button 2 clicked";
}
But, like I said (and others before me): don't use this code. Find a better solution.

Cheers,

Imar
__________________
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Follow me on Twitter

Author of Beginning ASP.NET 4.5 : in C# and VB, Beginning ASP.NET Web Pages with WebMatrix
and Beginning ASP.NET 4 : in C# and VB.
Did this post help you? Click the button below this post to show your appreciation!
The Following User Says Thank You to Imar For This Useful Post:
Gayathri79 (May 24th, 2010)