Find-Postback-control-in-asp.net-technothirsty

Find Postback control of Page in asp.net

Find Postback control of Page in asp.net

Problem: Let’s say your page has been posted back and you want to find from which control it has been initiated.

Solution: We have to put some check at Page_Load even of the page and traverse for all controls and match request with them. I have given sample code which is as below.

string controlID = getPostBackControlName();
if (controlID == null || controlID == "ControlID")
{
    //your code goes  here
}

private string getPostBackControlName()
{
    Control control = null;

    string ctrlname = Page.Request.Params["__EVENTTARGET"];
    if (ctrlname != null && ctrlname != String.Empty)
    {
        control = Page.FindControl(ctrlname);
    }
    else
    {
        string ctrlStr = String.Empty;
        Control c = null;
        foreach (string ctl in Page.Request.Form)
        {
            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;
            }
        }
    }
    if (control == null)
    {
        return null;
    }
    else
    {
        return control.ID;
    }
}

 

Leave a Reply