Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET :: During page_load, how can I get the ID of the control that submitted the postback?

During the Page_Load, I would like to capture the control that performed the postback.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {

    }

    // Capture the control ID here.
}

As usual, any ideas would be greatly appreciated!

like image 677
Andy Evans Avatar asked Dec 28 '22 14:12

Andy Evans


1 Answers

For anyone who might interested in this (at least what worked for me). Cen provided the answer.

In your Page_Load event add:

Control c= GetPostBackControl(this.Page); 

if(c != null) 
{ 
    if (c.Id == "btnSearch") 
    { 
        SetFocus(txtSearch); 
    } 
}

Then in your basepage code add:

public static Control GetPostBackControl(Page page)
{
    Control control = null;
    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != String.Empty)
    {
        control = page.FindControl(ctrlname);

    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }

    }
    return control;
}

You can see the original post here

Hope this helps.

like image 115
2 revs Avatar answered Jan 20 '23 09:01

2 revs