Which button was clicked?

Normally, you do not need to worry about detecting which control submitted a form on your asp.net web form, the framework takes care of it all for you as long as you wire up the event correctly.

For various reasons, sometimes you need to do it the old fashioned way.  I have seen a number of forums where people have asked how to do this, only to be met with a chorus of "You don't need to, use events instead."  Which is fair enough, but sometimes you have to assume that the enquirer knows what they are doing, and such responses are entirely unhelpful.  So if anyone is searching for the answer out there, here it is:
  1. Get the current request
  2. Interrogate the form on the request for the control (by id)
  3. If the value for an input control (of type submit) is not null (it will be populated with eg. the text on a button), then that is the control which initiated the POST of the form.

Example

if (HttpContext.Current.Request.Form.GetValues(_saveCloseButton.ClientID.ToString().Replace("__", "$_")) != null)
{
         SaveAndClose();
}
else if (HttpContext.Current.Request.Form.GetValues(_saveContinueButton.ClientID.ToString().Replace("__", "$_")) != null)
{
       SaveAndContinue();
}
else .....

NB:
  • The asp.net framework alters the id of the control, pre-pending the ids of parent controls in the control tree, so we need to use the ClientID property.
  • The ClientID needs some re-formatting due to how it returns (ie. with '$' signs) in the form collection
  • If you do not have runat='server' set, you can supply a hard-coded string id for the control.

I hope this helps someone out there.

Comments