简体   繁体   English

如何找出哪个按钮触发了回发?

[英]How do I find out which button triggered the postback?

In asp.net (c#) how can I find out which asp:button triggered the postback? 在asp.net(c#)中,我如何找出哪个asp:button触发了回发?

I am using it for dynamic controls and want to do a different process on pageload for different buttons. 我将其用于动态控件,并希望对不同按钮的页面加载执行不同的处理。 I have tried looking at __EVENTARGUMENTS etc. but they didnt work. 我尝试查看__EVENTARGUMENTS等,但是它们没有起作用。

I am looking to do something like this: 我正在寻找做这样的事情:

Page_load Case: Button 1 clicked //Do something Button 2 clicked //Do something Page_load案例:单击按钮1 //做某事按钮2单击//做某事

Use the below code. 使用下面的代码。

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

Calling this function: 调用此函数:

I have included the above function in a static class UtilityClass. 我已经将上述函数包含在静态类UtilityClass中。

String postBackControlId = UtilityClass.GetPostBackControlId(this);

The code has been referenced from Mahesh's Blog . 该代码已从Mahesh的Blog中引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM