shaun.breach
shaun.breach

Reputation: 229

Determining which control raised the postback

Any ideas how to check which control in an asp.net web application raised a postback?

I have a number of buttons, and want to perform a different task in the Page_Load method depending which button was clicked.

Upvotes: 0

Views: 1719

Answers (3)

seanzi
seanzi

Reputation: 883

To check which control caused the postback, use Request.Form["__EVENTTARGET"]. This should return a unique ID of the control that caused the postback.

EDIT For this to work you will have to set UseSubmitBehavior property of the button to false which causes it to use Asp Net post back mechanism

Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.

When the UseSubmitBehavior property is false, control developers can use the GetPostBackEventReference method to return the client postback event for the Button. The string returned by the GetPostBackEventReference method contains the text of the client-side function call and can be inserted into a client-side event handler.

From MSDN

Upvotes: 1

Andy Stannard
Andy Stannard

Reputation: 1703

Well in the method handler of the button the event it contains a reference to the button so you can get to the controls id:

protected void Button1_Click(object sender, EventArgs e)
{
  ((System.Web.UI.WebControls.Button)sender).ID
}

the EventArgs parameter contains the command name which can be used to identify what you need to do:

if (e.CommandName == "AddToCart")
{   
    Do something
}

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can get the Postback control id from the '__EVENTTARGET' value in the requist. params

Have a look at the following article.

Upvotes: 1

Related Questions