找出点击了哪个按钮的方法

Mat*_*001 2 c# asp.net events

我想知道在回发期间点击了什么按钮.

因此,如果用户单击按钮..它将进行回发,然后进入控件Click事件.

我想要做的是找出在第一阶段点击了什么按钮.在PostBack阶段.

有没有办法实现这一目标?

PS.仅限c#代码.这是一个asp.net问题

Tow*_*own 6

您可以使用与此类似的代码检查__EVENTTARGETForm收集(从这里无耻地被盗).

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;
}
Run Code Online (Sandbox Code Playgroud)

Page_Load像这样调用它:

Control controlThatCausedPostBack = GetPostBackControl(this);
Run Code Online (Sandbox Code Playgroud)