2

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:

  • Renaming the onClick event in both view and codebehind
  • Deleting onClick, going to the design tab, double click on the button to auto-generate a new event
  • Changing auto-event wireup from false to true

Pertinent questions for reference:

Please let me know if you need additional information.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Jacob Russell
  • 53
  • 2
  • 12
  • Two things you may try. 1. Make sure the namespace of the code behind class is correct. 2. Try clean solution, exit Visual Studio, reopen VS and rebuild the solution. – wannadream Dec 06 '18 at 16:11
  • The namespace was correct, and I tried a clean and restart, but the error persisted. – Jacob Russell Dec 13 '18 at 15:33

1 Answers1

3

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.

VDWWD
  • 35,079
  • 22
  • 62
  • 79
  • I gave this a try before and I got the same error; I should have put it in the things I tried section. There are additional events on the `OnInit`, and since I inherited this project I wanted to try and find a solution before changing the way the event registration is handled. I will revisit this solution and get back to you. – Jacob Russell Dec 06 '18 at 15:15
  • Turns out the server was not running the most updated code, and the event handler in the OnInit did not match the method name. Hence the click event I created could not be found since there was a different event handler already registered to that button. I removed the OnInit and switched to protected per your suggestion to reduce the redundancy and confusion. – Jacob Russell Dec 13 '18 at 15:31