【问题标题】:ASP.NET Web Forms ASP button OnClick Compiler Error (CS1061)ASP.NET Web 窗体 ASP 按钮 OnClick 编译器错误 (CS1061)
【发布时间】:2018-12-06 14:48:16
【问题描述】:

我收到以下错误:

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 按钮:

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

后面代码中的事件注册:

 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 事件:

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

我尝试过的事情:

  • 在视图和代码隐藏中重命名 onClick 事件
  • 删除onClick,进入设计选项卡,双击按钮自动生成新事件
  • 将自动事件连接从 false 更改为 true

相关问题供参考:

如果您需要更多信息,请告诉我。

【问题讨论】:

  • 您可以尝试两件事。 1. 确保类后面代码的命名空间是正确的。 2.尝试干净的解决方案,退出Visual Studio,重新打开VS并重建解决方案。
  • 命名空间是正确的,我尝试清理并重新启动,但错误仍然存​​在。

标签: c# asp.net webforms


【解决方案1】:

制作按钮点击方法protected

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

但是为什么所有的代码都在 OnInit 中呢?您在那里添加 Click 事件,但也将它放在 Button 本身上,所以它是非常多余的。您可以删除OnInitInitializeComponent,它仍然可以工作。

【讨论】:

  • 我之前试过这个,我得到了同样的错误;我应该把它放在我尝试过的东西部分。 OnInit 上还有其他事件,由于我继承了这个项目,我想在更改事件注册的处理方式之前尝试找到解决方案。我会重新审视这个解决方案并回复你。
  • 原来服务器没有运行最新的代码,并且 OnInit 中的事件处理程序与方法名称不匹配。因此无法找到我创建的单击事件,因为该按钮已经注册了一个不同的事件处理程序。我删除了 OnInit 并根据您的建议切换到 protected 以减少冗余和混乱。
猜你喜欢
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 2015-05-26
  • 1970-01-01
  • 2011-10-07
相关资源
最近更新 更多