ASP.NET determines which button was pressed inside the update panel in the page load event

I am trying to solve an ASP.NET UserControl page lifecycle issue. I have an update panel with two buttons. Now in the Page_Load event, I need to check to see which of the two buttons was pressed.

I know that you need to use the click event for this, but this is a case of a rather complex page loop with dynamically added controls, etc. etc., so this is not an option, unfortunately: - (

I tried to check the value Request.Form["__EVENTTARGET"], but since the buttons are inside the UpdatePanel, the value is an empty string (at least I think why it is empty)

So, is there a way to check which button was clicked in the UpdatePanel in the Page_Load event?

Thanks in advance.

All the best

Bo

+5
source share
1 answer

You can get the identifier of the control that caused the postback in the Page_Load event using this method.

    protected void Page_Load(object sender, EventArgs e)
    {
           Textbox1.Text = getPostBackControlID();    
    }   

    private string getPostBackControlID()
    {
        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; 
    }
}
+9
source

All Articles