Jacob Russell
Jacob Russell

Reputation: 63

ASP.NET Web Forms ASP button OnClick Compiler Error (CS1061)

I am getting the following error:

An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compile Error Message: CS1061: 'codebehind' does not contain a definition for 'btnSave_Click' and no extension method 'btnSave_Click' accepting a first argument of type 'codebehind' could be found (are you missing a using directive or an assembly reference?)

Screenshot of error

ASP button in the view:

<asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-success btn-md" Width="100px" OnClick="btnSave_Click" />

Event registration in the code behind:

 override protected void OnInit(EventArgs e)
    {
        btnSave.Click += new EventHandler(btnSave_Click);

        InitializeComponent();
        base.OnInit(e);
    }
    private void InitializeComponent()
    {
        this.Load += new System.EventHandler(this.Page_Load);
    }

OnClick Event:

private void btnSave_Click(object sender, EventArgs e)
    {
        //foo
    }

Things I have tried:

Pertinent questions for reference:

Please let me know if you need additional information.

Upvotes: 2

Views: 1438

Answers (1)

VDWWD
VDWWD

Reputation: 35514

Make the Button Click method protected.

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

But why all the code in the OnInit? You add the Click event there, but also have it on the Button itself, so it is quite redundant. You can remove the OnInit and InitializeComponent and it will still work.

Upvotes: 3

Related Questions