Category : .Net | Author : Chtiwi Malek | First posted : 3/13/2012 | Updated : 4/27/2012
Tags : asp.net, c#, postback
Finding the control that fired the Postback

Finding the control that fired the Postback

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.
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :