如何识别Page_Load中的回发事件

我们有一些遗留代码需要在Page_Load中识别哪个事件导致了回发。 目前,这是通过检查这样的请求数据来实现的……

if(Request.Form [“__ EVENTTARGET”]!= null
&&(Request.Form [“__ EVENTTARGET”]。IndexOf(“BaseGrid”)> -1 // BaseGrid事件(例如排序)
|| Request.Form [“btnSave”]!= null //保存按钮

如果有人重命名控件,这非常难看并且会中断。 有更好的方法吗?

重写每个页面以便它不需要在Page_Load中检查它当前不是一个选项。

这应该让你获得导致回发的控件:

public static Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if (ctrlname != null && ctrlname != string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } return control; } 

在此页面上阅读更多相关信息: http : //ryanfarley.com/blog/archive/2005/03/11/1886.aspx

除了上面的代码,如果控件是ImageButton类型,那么添加下面的代码,

 if (control == null) { for (int i = 0; i < page.Request.Form.Count; i++) { if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; } } } 

我只是发布整个代码(其中包括导致回发的图像按钮/附加控制检查)。 谢谢Espo。

 public Control GetPostBackControl(Page page) { Control control = null; string ctrlname = page.Request.Params.Get("__EVENTTARGET"); if ((ctrlname != null) & ctrlname != string.Empty) { control = page.FindControl(ctrlname); } else { foreach (string ctl in page.Request.Form) { Control c = page.FindControl(ctl); if (c is System.Web.UI.WebControls.Button) { control = c; break; } } } // handle the ImageButton postbacks if (control == null) { for (int i = 0; i < page.Request.Form.Count; i++) { if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; } } } return control; }