开发者

eventhandler and postback (.net)

开发者 https://www.devze.com 2023-04-11 04:42 出处:网络
开发者_如何学JAVAI have a simple asp.net-Page with a button. <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default2.aspx.cs\" Inherits=\"Default2\" MasterPageFile=\"~/MasterPage.mas
开发者_如何学JAVA

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?


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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号