You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决ASP.NET报错'default_aspx'不包含'Button1_Click'的定义

问题修复方案

你遇到的'default_aspx' 不包含 'Button1_Click' 的定义属于衍生报错,本质是后台Default.aspx.cs代码存在编译错误,导致页面对应类编译失败,前端无法识别类中定义的方法。你需要按以下步骤修改代码:

1. 修复连接字符串转义问题

C#中普通字符串内的反斜杠是转义符,不能直接写\,有两种合法写法可选:

  • 双反斜杠转义:
SqlConnection con = new SqlConnection("Data Source=DESKTOP\\SQLEXPRESS;Initial Catalog=StudentRecords;Integrated Security=True");
  • 逐字字符串(字符串前加@):
SqlConnection con = new SqlConnection(@"Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=StudentRecords;Integrated Security=True");

2. 补充缺失的命名空间引用

代码中用到了DataTable类,需要在Default.aspx.cs顶部添加对应的命名空间引用:

using System.Data;

3. 修复LoadRecord方法的变量作用域错误

你当前定义的con是Button1_Click方法内的局部变量,LoadRecord方法无法直接访问,需要调整LoadRecord的逻辑:

// To show inserted values in the grid view 
void LoadRecord()
{
    // 方法内单独创建数据库连接
    using (SqlConnection con = new SqlConnection(@"Data Source=DESKTOP\SQLEXPRESS;Initial Catalog=StudentRecords;Integrated Security=True"))
    {
        con.Open();
        SqlCommand comm = new SqlCommand("select * from StudentInfo_Tab", con);
        SqlDataAdapter d = new SqlDataAdapter(comm);
        DataTable dt = new DataTable();
        d.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

这里额外用using包裹连接对象,可以自动释放连接资源,不用手动写con.Close()。

4. (可选优化)修复SQL注入风险

你当前的插入逻辑是直接拼接用户输入的内容到SQL语句,存在严重的SQL注入风险,建议改成参数化查询:

SqlCommand comm = new SqlCommand("Insert into dbo.StudentInfo_Tab values(@StuId,@StuName,@Address,@Age,@Contact)", con);
comm.Parameters.AddWithValue("@StuId", int.Parse(TextBox1.Text));
comm.Parameters.AddWithValue("@StuName", TextBox2.Text);
comm.Parameters.AddWithValue("@Address", DropDownList1.SelectedValue);
comm.Parameters.AddWithValue("@Age", double.Parse(TextBox3.Text));
comm.Parameters.AddWithValue("@Contact", TextBox4.Text);

所有修改完成后重新编译项目,报错就会消失。


内容的提问来源于stack exchange,提问作者Brute

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:24:04