Does Asp.Net contain no definition for buttonClick?

I try to create a program on visual studio asp.net, but whenever I try to click a button with an OnClick event, I get the following error:

"CS1061:" ASP.test_aspx "does not contain a definition for" buttonClick ", and the buttonClick extension method cannot be found that accepts the first argument of type" ASP.test_aspx "(do you miss the using directive or the assembly reference?)"

Here is my HTML for reference:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="MRAApplication.test" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button id="b1" Text="Submit" runat="server" OnClick="buttonClick" /> <asp:TextBox id="txt1" runat="server" /> </div> </form> </body> </html> 

and here is my code:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MRAApplication { public partial class test : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } void buttonClick(Object sender, EventArgs e) { txt1.Text = "Text"; } } } 

Please keep the explanations as simple as possible as I am new to coding. Thanks for any help. :)

+8
c # onclick
source share
3 answers

You need to declare the event handler as protected:

 protected void buttonClick(Object sender, EventArgs e) { txt1.Text = "Text"; } 

Markup is essentially a class that inherits from the code behind. For members to be available, they must be protected or publicly.

+14
source share

You should make this at least secure:

 protected void buttonClick(Object sender, EventArgs e) { txt1.Text = "Text"; } 

The default access for everyone in C # is "the most restricted access you could declare for this member", therefore private for the method.

Since aspx is a child of your codebehind ( Inherits ) class, any method that you want to get from aspx must be declared protected or public (at least in C #, VB.NET has Handles ).

Reading:

+3
source share

You need to declare an event handler, you can do this in several ways:

 protected void Page_Load(object sender, EventArgs e) { btnNote.Click += new EventHandler(btnNote_Click); } void btnAddNote_Click(object sender, EventArgs e) { // Do Stuff. } 

So, as you can see, declaring the event on the Load page, you can use raw void , as you already above. Otherwise, you need to declare it protected .

 protected void btnAddNote_Click(object sender, EventArgs e) { // Do Stuff. } 
+2
source share

All Articles