与这个问题相关:在PostBack时,如何在Page_Init事件中检查哪个控件引起PostBack
如果控件被包含在ASP.NET AJAX UpdatePanel中,“control”变量是空的,因为它在AJAX PostBack后有不同的ID。是否有解决方案可以在ASP.NET Ajax UpdatePanel内获取触发Postback的控件?
public static string GetPostBackControlName( Page page ) {
Control control = null;
/**
* First we will check the "__EVENTTARGET" because if the postback is made
* by controls which used the _doPostBack function, it will be available in the Request.Form collection.
*/
string ctrlname = page.Request.Params["__EVENTTARGET"];
if ( !String.IsNullOrEmpty( ctrlname ) ) {
control = page.FindControl( ctrlname );
} else {
/**
* If __EVENTTARGER is null, the control is a button-type and
* need to iterate over the form collection to find it.
*/
Control c = null;
string ctrlStr = null;
foreach ( string ctl in page.Request.Form ) {
if ( ctl.EndsWith( ".x" ) || ctl.EndsWith( ".y" ) ) {
/**
* ImageButtons have an additional "quasi-property" in their ID which identifies
* the mouse-coordinates (X and Y).
*/
ctrlStr = ctl.Substring( 0, ctl.Length - 2 );
c = page.FindControl( ctrlStr );
} else {
c = page.FindControl( ctl );
}
if ( c is Button || c is ImageButton ) {
control = c;
break;
}
}
}
if ( control != null ) {
return control.ID;
}
return string.Empty;
}