哪个控件导致回发?

hhh*_*112 34 asp.net postback

我有两个按钮:

<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Button ID="Button2" runat="server" Text="Button" />
Run Code Online (Sandbox Code Playgroud)

如何在pageLoad上确定这两个中的哪一个导致回发?是否有一个简短的解决方案,因为我知道只有两个控件可以导致此回发?

Jam*_*son 56

您可以使用此方法来获取导致回发的控件:

/// <summary>
/// Retrieves the control that caused the postback.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
private Control GetControlThatCausedPostBack(Page page)
{
    //initialize a control and set it to null
    Control ctrl = null;

    //get the event target name and find the control
    string ctrlName = page.Request.Params.Get("__EVENTTARGET");
    if (!String.IsNullOrEmpty(ctrlName))
        ctrl = page.FindControl(ctrlName);

    //return the control to the calling method
    return ctrl;
}
Run Code Online (Sandbox Code Playgroud)

  • 在许多情况下返回null.正确的解决方案是:http://stackoverflow.com/questions/3175513/on-postback-how-can-i-check-which-control-cause-postback-in-page-init-event (4认同)
  • 正如 OP 所要求的那样,这对按钮有何作用?当回发由按钮引起时,`__EVENTTARGET` 只是一个空字符串 (2认同)

Fra*_*Thu 12

http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx

private string getPostBackControlName()
    {
        Control control = null;
        //first we will check the "__EVENTTARGET" because if post back made by       the controls
        //which used "_doPostBack" function also available in Request.Form collection.

        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 they having an additional "quasi-property" in their Id which identifies
                //mouse x and y coordinates
                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;
                }
            }

        }

        if (control != null)
            return control.ID;
        else
            return string.Empty;
    }
Run Code Online (Sandbox Code Playgroud)