.Net, ASP.Net, C#, VB.net, SQL Server, Xml, CSS, Design Patterns related tips, tricks, code snippets, articles, links, thoughts, etc. from Binu & Subi Thayamkery.

Binu Thayamkery is a seasoned software architect with more than 13 years of experience in developing enterprise grade connected systems using Microsoft Technologies. In his current position as a lead consultant-solution architect with Prudential Financial, he is working on architecture of next generation investment reporting framework using .net 3.5/WCF/AJAX, etc. He holds a Masters Degree in Computer Science from Colorado State University. Subi Thayamkery is an experienced software developer with more than 8 years of developing various application software systems ranging from workflow automation systems to compliance management tools. She currently works as a technology consultant for Prudential Financial where she helps develop a new system for corportate governance department. She holds an Electrical Engineering degree from New Jersey Institute of Technology.

Tuesday, March 28, 2006

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!

0 comments: