0

在 asp.net (c#) 中,我如何找出哪个 asp:button 触发了回发?

我将它用于动态控件,并希望在页面加载时为不同的按钮执行不同的过程。我曾尝试查看 __EVENTARGUMENTS 等,但它们没有用。

我想做这样的事情:

Page_load Case: Button 1 clicked //做某事 Button 2 clicked //做某事

4

1 回答 1

-2

使用下面的代码。

  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 Button || foundControl is ImageButton)) continue;

                    control = foundControl;
                    break;
                }
            }

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

调用这个函数:

我已将上述函数包含在静态类 UtilityClass 中。

String postBackControlId = UtilityClass.GetPostBackControlId(this);

该代码已从Mahesh 的博客中引用。

于 2013-10-29T11:15:54.603 回答