Loading ...

How to find which control caused postback | CodeAsp.Net

How to find which control caused postback

 /5
0 (0votes)

To find that which control caused postback, the following example might help you.

I am giving example on page load event when postback takes place.

 

protected void Page_Load(object sender, EventArgs e)
{
//on every postback you can print the ID of the control which caused postback
if (IsPostBack)
{
Control ctl = GetPostBackControl(Page);
if (ctl != null)
Response.Write(ctl.ID);
}
}

 

//method that Identify the postback control
public static Control GetPostBackControl(System.Web.UI.Page page)
{
Control control = null;
string ctrlname = page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = page.FindControl(ctrlname);
}
// if __EVENTTARGET is null, the control is a button type and we need to
// iterate over the form collection to find it
else
{
string ctrlStr = String.Empty;
Control c = null;
foreach (string ctl in page.Request.Form)
{
// handle ImageButton controls ...
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = page.FindControl(ctrlStr);
}
else
{
c = page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
return control;
}

 

Comments (no comments yet)

Top Posts