eventhandler and postback (.net)
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);
}
精彩评论