Over a million developers have joined DZone.

Discover which Control Raised a PostBack

·

Yesterday I  needed a solution for an annoying problem. I have some buttons on a ASP.NET web form and I need to know which button raised the postback not in the event itself but in the page load event. This post will show a way to solve this conundrum.

Discover which Control Raised a PostBack

When we use ASP.NET and we have ASP buttons on the page if we want to do something before their postback event happen we need to discover whether they raised a postback. Since an ASP button uses the form.submit() method on the client side then on the server side the Page.Request.Params[“__EVENTTARGET”] will return null. The following method will discover which control raised a postback:

private Control GetControlThatRaisedPostBack()
{
string id = Page.Request.Params["__EVENTTARGET"];

if (!string.IsNullOrEmpty(id))
{
return Page.FindControl(id) as Control;
}

foreach (var ctlID in Page.Request.Form.AllKeys)
{
Control c = Page.FindControl(ctlID) as Control;
if (c is Button)
{
return c;
}
}

return null;
}

As you can see if the control isn’t a button then it will have __EVENTTARGET which will be handled first. If we deal with ASP buttons then we need to iterate on the form keys and through them we will find the button. This is because when a button is clicked it uses the form.submit() method. That method add the button to the list of elements that are submitted in the form (and only the button that called the submit and no other buttons).

Summary

Finding which control raised a postback in the form outside the postback event can be very annoying. I hope that the method I provided will be helpful to you.

 

Topics:

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}