9

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. :)

JaGo
  • 257
  • 1
  • 4
  • 12
  • See: http://stackoverflow.com/questions/9397824/why-private-vs-protected-for-how-a-button-click-event-is-created-in-asp-net-usin – Habib Aug 28 '14 at 14:29

3 Answers3

14

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.

GarlicFries
  • 8,095
  • 5
  • 36
  • 53
Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
2

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:

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

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.
}
Greg
  • 11,302
  • 2
  • 48
  • 79