C# 在页面期间识别。加载是否要处理按钮单击事件
我有一个ASPX网页,上面有一个按钮。用户单击此按钮后,请求将提交到服务器,并执行按钮单击事件处理程序 我有一些必须驻留在Page.Load上的逻辑,但这个逻辑取决于是否通过单击按钮提交了请求。基于页面加载后执行的事件处理程序C# 在页面期间识别。加载是否要处理按钮单击事件,c#,asp.net,.net,event-handling,C#,Asp.net,.net,Event Handling,我有一个ASPX网页,上面有一个按钮。用户单击此按钮后,请求将提交到服务器,并执行按钮单击事件处理程序 我有一些必须驻留在Page.Load上的逻辑,但这个逻辑取决于是否通过单击按钮提交了请求。基于页面加载后执行的事件处理程序 问题:如何在页面加载中找出页面加载后将执行哪些事件处理程序?可能有更好的解决方案。是否希望代码仅在页面首次加载且使用回发时运行?如果是,请检查属性。如果代码不需要在其他事件处理程序之前运行,请将其移动到,因为它在事件处理程序之后触发。@akton的答案可能是您应该做的,但
问题:如何在页面加载中找出页面加载后将执行哪些事件处理程序?可能有更好的解决方案。是否希望代码仅在页面首次加载且使用回发时运行?如果是,请检查属性。如果代码不需要在其他事件处理程序之前运行,请将其移动到,因为它在事件处理程序之后触发。@akton的答案可能是您应该做的,但如果您想取消保留并确定是什么导致在生命周期早期回发,您可以查询回发数据以确定单击了什么。但是,这不会给出事件处理期间将执行的实际函数/处理程序 首先,如果不是
按钮
/图像按钮
导致回发,则控件的ID将位于\u EVENTTARGET
中。如果一个按钮
导致了回发,那么ASP.NET会做一些“可爱”的事情:它会忽略所有其他按钮,以便表单上只显示单击的按钮。ImageButton
有点不同,因为它会发送坐标。一个实用功能,可包括:
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;
}
公共静态控件GetPostBackControl(第页)
{
控件postbackControlInstance=null;
字符串postbackControlName=page.Request.Params.Get(“\uu EVENTTARGET”);
if(postbackControlName!=null&&postbackControlName!=string.Empty)
{
postbackControlInstance=page.FindControl(postbackControlName);
}
其他的
{
//处理按钮控件回发
for(int i=0;i
尽管如此,如果您可以重构控件/页面以延迟执行,那么如果您使用@akton建议的范例,您的代码将更干净/更健壮。这些帮助了我很多:我想从我的gridview保存值,它正在重新加载我的gridview/覆盖我的新值,因为我已经在我的页面加载中使用了IsPostBack
if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{ //Do not reload the gridview.
}
else { reload my gridview. }
资料来源: