开发者

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.

Wh开发者_JAVA百科at 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


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);


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜