在asp.net(c#)中,如何找出哪个asp:按钮触发了回发?
我正在将它用于动态控件,并希望针对不同的按钮对页面加载执行不同的处理。我曾尝试查看__EVENTARGUMENTS等,但他们没有工作。
我希望做这样的事情:
的Page_Load 案件: 按钮1单击 //做一点事 单击按钮2 //做点什么
答案 0 :(得分:-1)
使用以下代码。
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's Blog 引用。