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:
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 need to declare your event handler, you can do that a couple ways:
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 aprotected
.You have to make it at least protected:
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 asprotected
orpublic
(at least in C#, VB.NET hasHandles
).Read: