Tuesday, September 26, 2006

Which control caused postback in asp.net

ASP.NET server controls has a property named AutoPostBack. If we set AutoPostBack property of any ASP.NET server control to True then whenever this control is clicked page is posted back to the server automatically. Sometimes we need to find which control on the server caused the post back.

In ASP.NET, Request object contains a property named __EVENTTARGET that tells us which control caused the post back. It gives back ID of the control which caused the past back. You can try like this Request[“__EVENTTARGET”].

Note: there are two underscore characters before the EVENTTARGET text.

If you are using simple controls which do not contain other controls and you want to find the name of the control which caused the postback then you can simple use the following line of code

Response.Write(Request["__EVENTTARGET"]);

Or you can get the value in some text variable as given below.

string itemCausedPostback = Request["__EVENTTARGET"];

In case you are using some control which is actually a collection of controls then the way is slightly different. For example you are using a CheckBoxList control, which contains AutoPostBack property set to True. Now, if you want to find which checkbox caused the post from with in the list then try this.


First of all get the value of the EVENTTARGET property in some variable

string itemCausedPostback = Request["__EVENTTARGET"];


Now get the index of “:” sign from the string, because the part before the “:” is the name of the control and the part after the “:” is the index of the control with in the list. Now, get substring starting right from the next character of the colon and having length till end of the string.

int startIndex = itemCausedPostback.IndexOf(":")+1;
int length = itemCausedPostback.Length - startIndex;

int indexId = Convert.ToInt32(itemCausedPostback.Substring(startIndex,length));
Now you can use this indexId as an index of the CheckBoxList item.
Response.Write(this.CheckBoxList1.Items[indexId].Text);

For example you clicked the second item in the list the indexId will contain 1 and the this.CheckBoxList1.Items[indexId].Text will give the text of the item at that index.

1 comment:

RobMac said...

Interesting post. Any idea how to get the same result when doing a partial page postback inside an Ajax.Net UpdatePanel?