Discover which Control Raised a PostBack

  • submit to reddit

Gil Fink is an expert in ASP.NET and Microsoft data platform and serves as a Senior .Net Consultant and Architect at Sela Group. He is a Microsoft data platform MVP and a certified MCPD Enterprise Application Developer. Gil has worked in the past in variety of positions and projects as a leading developer, team leader, consultant and more. His interests include Entity Framework, Enterprise Library, WCF, LINQ, ADO.NET and many other new technologies from Microsoft. You can find his Blog here: http://www.gilfink.net Gil is a DZone MVB and is not an employee of DZone and has posted 92 posts at DZone. You can read more from them at their website. View Full User Profile

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.

 

References
0
Average: 5 (1 vote)
Tags:

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)