Monday, 9 November 2015

check which control fired post back at pageload

If you want to know which controlled fired post back at page load, here is some sample code.

1) for link button:

string ctrlname = Page.Request.Params["__EVENTTARGET"];
                        if ((!string.IsNullOrWhiteSpace(ctrlname)) && ctrlname.EndsWith("lnkSelect"))
                        {
                            LinkButton lnk1 = Page.FindControl(ctrlname) as LinkButton;
                         }

2) for Image button and Button:

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            Response.Write(getPostBackControlName());
    }

   
    private string getPostBackControlName()
    {
        Control control = null;
        //first we will check the "__EVENTTARGET" because if post back made by       the controls
        //which used "_doPostBack" function also available in Request.Form collection.
        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 they having an additional "quasi-property" in their Id which identifies
                //mouse x and y coordinates
                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.ID;

    }
}

2 comments:

  1. Thanks for sharing such useful information. I really appreciate your blog post. If you provide customer support, you likely need an Office 365 help desk ticketing system that helps you manage, organize and execute on customer support tickets.

    ReplyDelete
    Replies
    1. Thanks for your response. I appreciate your feedback.

      Delete