Matrix001
Matrix001

Reputation: 1272

Way to find out which button was clicked

I want to find out what button was clicked during post back.

So if the user clicks a button.. It goes to postback, then to the controls Click event.

What I want to do is to find out what button was clicked during the first stage. During the PostBack stage.

Is there a way to achieve that?

ps. c# code only. It is an asp.net question

Upvotes: 2

Views: 5891

Answers (2)

Town
Town

Reputation: 14906

You can check __EVENTTARGET and the Form collection with code similar to this (shamelessly stolen from here).

public static System.Web.UI.Control GetPostBackControl(System.Web.UI.Page page)
{
    Control control = null;
    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 controls ...
            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;
}

Call it in Page_Load like this:

Control controlThatCausedPostBack = GetPostBackControl(this);

Upvotes: 6

wsanville
wsanville

Reputation: 37516

Just use a private variable on your web page. In the OnClick handler, set the value of that variable to the sender argument (you'll need to typecast it to a Button or Control).

Upvotes: 0

Related Questions