How to find out which webcontrol generated postback?


There will be instances where this information could come handy. You are doing some action specific to a control on postback and don’ t want that to happen when postback happens because of some other control. Trick to figure out this is to understand how ASP.Net postback works. When ASP.Net renders HTML, it creates a block
of Javscript that looks like this,

1 function __doPostBack(eventTarget, eventArgument)
2 {
3 var theform = document.Form1;
4 theform.__EVENTTARGET.value = eventTarget;
5 theform.__EVENTARGUMENT.value = eventArgument;
6 Form1.submit();
7 }

When any controls generates a postback (example: Button Click), this Javscript is called and values are set to the hidden variables named __EVENTTARGET and __EVENTARGUMENT. __EVENTTARGET is the control that is doing the postback and __EVENTARGUMENT holds any additional information for that event. Now, with this information, it is easily understood how to use this at server side Page_Load event to determine which control caused the postback.

This is done by examining the request obejct to see the values in __EVENTTARGET.

1 char[] delim = {'_'};
2 string[] pbCtrl = Request.Form["__EVENTTARGET"].Split(delim);
3 System.Diagnostics.Debug.WriteLine (pbCtrl[0]);
4

pbCtrl[0] should contain the ID of the control that triggered this postback!

Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s