如果要处理按钮点击事件,则在Page.Load期间识别

我有ASPX网页,上面有一个按钮。 用户单击此按钮后,将请求提交给服务器并执行按钮单击事件处理程序。

我有一些必须驻留在Page.Load上的逻辑,但是这个逻辑取决于是否通过按钮点击提交了请求。 基于页面生命周期事件处理程序在页面加载后执行。

问题 :如何在页面加载中找出页面加载后要执行的事件处理程序?

@ akton的答案可能就是你应该做的,但是如果你想要退出预订并确定在生命周期的早期导致回发的原因,你可以查询回发数据以确定点击的内容。 但是,这不会为您提供在事件处理期间将执行的实际函数/处理程序。

首先,如果Button / ImageButton以外的其他内容导致回发,则控件的ID将位于__EVENTTARGET 。 如果一个Button导致了回发,那么ASP.NET会有一些“可爱的”:它会忽略所有其他按钮,这样只有单击的按钮才会显示在表单上。 ImageButton有点不同,因为它会发送坐标。 实用function可以包括:

 public static Control GetPostBackControl(Page page) { Control postbackControlInstance = null; string postbackControlName = page.Request.Params.Get("__EVENTTARGET"); if (postbackControlName != null && postbackControlName != string.Empty) { postbackControlInstance = page.FindControl(postbackControlName); } else { // handle the Button control postbacks for (int i = 0; i < page.Request.Form.Keys.Count; i++) { postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]); if (postbackControlInstance is System.Web.UI.WebControls.Button) { return postbackControlInstance; } } } // handle the ImageButton postbacks if (postbackControlInstance == 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"))) { postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length-2) ); return postbackControlInstance; } } } return postbackControlInstance; } 

所有这一切,如果您可以重构您的控件/页面以延迟执行,如果您使用@akton建议的范例,您的代码将更清晰/更强大。

可能有更好的解决方案。 您是否希望代码仅在首次加载页面时运行并且您正在使用回发? 如果是,请检查Page.IsPostBack属性。 如果代码不需要在其他事件处理程序之前运行,则将其移动到OnPreRender,因为它在事件处理程序之后触发。

这些对我帮助很大:我想从gridview中保存值,它正在重新加载我的gridview /覆盖我的新值,因为我在PageLoad中有IsPostBack。

 if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null) { //Do not reload the gridview. } else { reload my gridview. } 

消息来源: http : //bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked