eventhandler and postback (.net)

让人想犯罪 __ 提交于 2019-12-13 01:24:57

问题


I have a simple asp.net-Page with a button.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" MasterPageFile="~/MasterPage.master"%>

<asp:Content runat="server" ID="content" ContentPlaceHolderID="ContentPlaceHolder1">

<asp:Button runat="server" ID="btn1" Text="Click me" />

</asp:Content>

with Code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        btn1.Click += new EventHandler(Btn1_Click);
    }
}

protected void Btn1_Click(Object sender, EventArgs e)
{
    //do stuff
}

The Click event is not raised when I click the button, but it is if I put the event in markup of button OR if I bind the EventHandler with postbacks. Why? I still don´t get it. Should the event not be raised independently of its source?


回答1:


I'm not 100% sure this is what you're asking, but: If you're not wiring up the Event Handler every time the page is loaded, it won't run. If you think AutoEventWireUp should be doing it, that's not what it's for. To clarify, the description for AutoEventWireup says

'Automatic binding is performed only for page events, not for events for controls on the page."

It either needs to be declared on the control itself:

<asp:Button runat="server" ID="btn1" Text="Click me" OnClick="Btn1_Click" />

Or you need to remove the!Page.IsPostback, and bind the event handler on each load.

protected void Page_Load(object sender, EventArgs e)
{
    btn1.Click += new EventHandler(Btn1_Click);
}


来源:https://stackoverflow.com/questions/7686413/eventhandler-and-postback-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!