简体   繁体   中英

C# Button Click

I have the following button on a .aspx page:

<asp:Button runat="server" ID="bntLogin" OnClick="bntLogin_Click" Text="Login" />

With the following in the .aspx.cs:

protected void bntLogin_Click(object sender, EventArgs e)
        {
           //
        }

When I try to build it I get the following error:

'ASP.reserve_aspx' does not contain a definition for 'bntLogin_Click' and no extension method 'bntLogin_Click' accepting a first argument of type 'ASP.reserve_aspx' could be found (are you missing a using directive or an assembly reference?)

However, when I move the click event from the code-behind to a script block inside the markup it builds.

Any ideas?

Are you sure that you placed the method in the correct code-behind file?

Check which file you are using as your code-behind file by looking at the @page directive at the top of the aspx file itself (check the inherits attribute) - you may be surprised.


A loosely-related side note: By setting the OnClick with a string value that corresponds to the method you wish to invoke you are implicitly relying on ASP.NET's AutoEventWireup feature which I don't consider to be a good approach. It is better to manually wire up your controls in your page's OnInit override method like this:

bntLogin.Click += bntLogin_Click;

By relying on AutoEventWireup you are allowing the ASP.NET runtime to create this code for you and since this happens at execution time you are incurring an execution time performance penalty as well as risking an exception like the one you are seeing now.

我通常将事件关联到代码隐藏的OnInit方法中,该方法是ASP.NET 1.1的保留(设计人员可以将其放回原处。)

如果您仍然有机会运行ASP.NET 1.1,请删除aspnet_client文件夹,然后重新生成并重试。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM