Archive

Archive for the ‘Web Programming’ Category

How to check which control has caused Post Back !

October 9, 2006 13 comments

My this post will be how to get the control that caused the Post back in ASP.NET code behind. I got this help from this page, all my courtesies to this guy :).

We will have to access the __EVENTTARGET element of the form. If any one has ever seen a client side HTML source of server side HTML code he/she must be familiar with __EVENTTARGET. A hidden tag is added to the form named __EVENTTARGET after a postback. This hidden input is set to the name of the control that was clicked in the __doPostBack JavaScript function(causing postback) and then the form is submitted. We can access this hidden input from our code-behind as it is submitted with the form and can be found in the Params or Form collections. This is how we get the control that caused a postback. Once we have the name you can get a reference to the control via FindControl and use it as needed.

string ctrlname = page.Request.Params.Get(“__EVENTTARGET”);
if (ctrlname != null && ctrlname != string.Empty)
{
return this.Page.FindControl(ctrlname);
}

The only problem of this method is if post back is caused by a button control. This is because a button is rendered as an input type=”submit” tag, and this causes the form to submit only, so a post back is not occured. Thus button will be added to the form collection of the page. So we can get this very control by a little bit of programming logic. So the code will be some like follows.

public static Control GetPostBackControl(Page page)
{
Control control = null;

string ctrlname = page.Request.Params.Get(“__EVENTTARGET”);
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}

This method takes a parameter which is a reference to the Page, it then uses that to look for the control that caused the postback. You can easily use this as follows:

Control c = PageUtility.GetPostBackControl(this.Page);
if (c != null)
{
//…
}

Advertisements