I am attempting to build 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 no extension method 'buttonClick' accepting a first argument of type 'ASP.test_aspx' could be found (are you missing a using directive or an 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 behind:
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 explanations as simple as possible as I am new to coding. Thank you for any and all help. :)
You need to declare your event handler as protected:
protected void buttonClick(Object sender, EventArgs e)
{
txt1.Text = "Text";
}
The markup is essentially a class that inherits from the code behind. In order for members to be accessible, they need to be protected or public.
You have to make it at least protected:
protected void buttonClick(Object sender, EventArgs e)
{
txt1.Text = "Text";
}
The default access for everything in C# is "the most restricted access you could declare for that member", so private
for a method.
Since the aspx is a child class of your codebehind class(Inherits
) any method that you want to access from the aspx must be declared as protected
or public
(at least in C#, VB.NET has Handles
).
Read:
You need to declare your event handler, you can do that a couple 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 by declaring the event at Page Load, you can use the raw void
like you have above. Otherwise you'll need declare it in a protected
.
protected void btnAddNote_Click(object sender, EventArgs e)
{
// Do Stuff.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With