views:

24

answers:

4

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!

A: 

If there's a way to do that, I'd love to know it too!

However, you can set up event handlers for each of the controls that can generate the postback, and handle events as they come in.

The problem with that is that these events are handled after Page_Load. So what you need to do in this approach is add a handler for Page_PreRender, and process the control input there. In the page life cycle, control events are after Load, but before PreRender.

Cylon Cat
+2  A: 

You can usually look at Request.Params["__EVENTTARGET"]. This variable will be populated as the result of the postback, and will hold the UniqueID of the control that caused it.

Unfortunately this doesn't work for button or imagebutton controls. For what looks to be a pretty robust method for getting it in these cases, you could check out this blog post.

womp
+1  A: 

You can use Request["__EVENTTARGET"] to get the ID of the control that invoked the postback.

M4N
A: 

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.

Andy Evans
If there are two buttons in the same form... Will your code be able to find which one caused it... If yes, could you please explain how?
The King
Yes. The control name is read from page.Request.Params.Get("__EVENTTARGET")
Andy Evans