Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET determine which button was clicked inside an updatepanel in page load event

I'm trying to get my head around a page lifecycle issue of an ASP.NET UserControl. What I have is an updatepanel with two buttons in it. Now, in the Page_Load event I need to make a check to see which of the two buttons was clicked.

I do know that I should use the click event for this, but this is a case of quite a complex page cycle with dynamically added controls and so on, so forth, so that is not an option, unfortunately :-(

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

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

Thanks in advance.

All the best,

Bo

like image 964
bomortensen Avatar asked Jul 04 '12 17:07

bomortensen


1 Answers

You can get ID of control which caused postback in the Page_Load event by 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; 
    }
}
like image 141
Adil Avatar answered Nov 16 '22 04:11

Adil