Monday, July 5, 2010

Determining the Control that Caused a PostBack in pageload

This article is for find which contorl that caused a post back.

Some times you might need to perform some action on an ASP.NET postback based on the control that caused the postback to occur. Some scenarios for this might include a form with many regions, each having it's own CustomValidator and the ability to perform a postback when a button for the section is clicked. Another scenario might be to set focus back to the control that caused the postback.

By using below methode we will find the which control has triggred post back.

public static Control GetPostBackControl(Page page)
{

Control postbackControlInstance = null;

string postbackControlName = page.Request.Params.Get("__EVENTTARGET");

if (postbackControlName != null && postbackControlName != string.Empty)
{
postbackControlInstance = page.FindControl(postbackControlName);
}

else
{
// handle the Button control postbacks

for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);

if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
return postbackControlInstance;
}
}
}

// handle the ImageButton postbacks

if (postbackControlInstance == null)
{
for (int i = 0; i < page.Request.Form.Count; i++)
{
if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}

return postbackControlInstance;

}

Above 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 cause = GetPostBackControl(this.Page);

No comments:

Post a Comment