Sometimes, when you have many controls on your page that can cause postbacks you need to know which control caused the page postback. Unfortunately Buttons, Image buttons, Checkboxes, Lists … behave in different ways.
Here is how to find it, this function will return the Control’s ID :
protected string PBControlID()
{
if (IsPostBack)
{
string CtlName = Page.Request.Params.Get("__EVENTTARGET");
if (!string.IsNullOrEmpty(CtlName))
{
// Looking for the control ID
return Page.FindControl(CtlName).ClientID;
}
else
{
// Looking for the button ID
foreach (string ctl in Page.Request.Form)
{
Control Ctl = Page.FindControl(ctl);
if (Ctl is System.Web.UI.WebControls.Button)
{
return Ctl.ClientID;
}
}
// Looking for the ImageButton ID
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")))
{
return Page.FindControl(Page.Request.Form.Keys[i].Substring(0, Page.Request.Form.Keys[i].Length - 2)).ClientID;
}
}
}
}
return "";
}
It is important not to name controls with ‘.x’ or ‘.y’ suffix, because this code looks for values in the Page.Request.Form collection ending with ‘.x’ or ‘.y’ to find the ImageButton that fired postback.