将事件处理程序添加到内容页面
我已在内容页
中的母版页
上连接了Button
控件,如下所示:
SiteMaster MasterPage;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MasterPage = (SiteMaster)Page.Master;
MasterPage.Button1.Click += new EventHandler(Button1_Click);
}
}
void Button1_Click(object sender, EventArgs e)
{
MasterPage.Button1_Click(sender, e);
}
但是,每当我单击Button1 在页面上(在 localhost 下运行),将触发
Page_Load
事件!
我做错了什么?
如果有帮助,MasterPage.Button1_Click
事件会运行登录脚本,因此不应出现递归调用。
I have wired up the Button
control on my Master Page
in the Content Page
as follows:
SiteMaster MasterPage;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MasterPage = (SiteMaster)Page.Master;
MasterPage.Button1.Click += new EventHandler(Button1_Click);
}
}
void Button1_Click(object sender, EventArgs e)
{
MasterPage.Button1_Click(sender, e);
}
However, whenever I click Button1
on the page (running under localhost), the Page_Load
event fires!
What have I done wrong?
If it helps, the MasterPage.Button1_Click
event runs a log in script, so there should be no recursive calls.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题是处理程序
Button1_Click
没有为您触发吗?如果是这样,原因是您仅在初始页面加载时而不是在页面回发时为
Click
事件分配事件处理程序。尝试在初始加载和后续回发时分配事件处理程序,如下所示:
希望这会有所帮助。
Is the issue here that the handler
Button1_Click
is not firing for you?If so, the reason for this is because you are only assigning the event handler for the
Click
event on initial page load and not when the page is posting back.Try assigning the event handler on initial load and subsequent postbacks like so:
Hope this helps.
也许您想在 Page_Init 中连接事件,而不是在 Page_Load 中。
只要您的按钮单击导致 Page_Load 触发。 Page_Load 总是会被触发,因为它是页面生命周期的一部分。
请参阅:http://support.microsoft.com/kb/305141 了解页面生命周期详细信息。
另请参阅问题: 在 asp.net 中,page_load在单选按钮 OnCheckedChanged 事件之前发生
Perhaps you want to wire your event up in the Page_Init as opposed to the Page_Load.
as far as your button click causing Page_Load to fire. Page_Load is always going to get fired because it's part of the page lifecycle.
see: http://support.microsoft.com/kb/305141 for page lifecycle details.
see also question: In asp.net, page_load occuring before radio button OnCheckedChanged event