一尘不染

在回发时,如何检查Page_Init事件中哪个控件导致回发

c#

在回发时,如何检查Page_Init事件中哪个控件导致回发。

protected void Page_Init(object sender, EventArgs e)
{
//need to check here which control cause postback?

}

谢谢


阅读 170

收藏
2020-05-19

共1个答案

一尘不染

我看到已经有一些很好的建议和方法建议如何获得回发控制。但是,我发现了另一个网页(Mahesh博客),该网页具有一种检索回发控件ID的方法。

我将在此处进行一些修改,包括使其成为扩展类。希望它以这种方式更有用。

/// <summary>
/// Gets the ID of the post back control.
/// 
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
    if (!page.IsPostBack)
        return string.Empty;

    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 controlName = page.Request.Params["__EVENTTARGET"];
    if (!String.IsNullOrEmpty(controlName))
    {
        control = page.FindControl(controlName);
    }
    else
    {
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it

        // ReSharper disable TooWideLocalVariableScope
        string controlId;
        Control foundControl;
        // ReSharper restore TooWideLocalVariableScope

        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"))
            {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            }
            else
            {
                foundControl = page.FindControl(ctl);
            }

            if (!(foundControl is IButtonControl)) continue;

            control = foundControl;
            break;
        }
    }

    return control == null ? String.Empty : control.ID;
}

更新(2016-07-22): 键入check for
ButtonImageButton更改为寻找IButtonControl以识别来自第三方控件的回发。

2020-05-19