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

ASP.NET GridView删除按钮触发Object Reference异常问题求助

问题根因

判断完全正确,触发RowDeleting事件时点击的是删除按钮,并未触发行选择逻辑,因此EduGrid.SelectedRow为null,访问其属性就会抛出空对象引用异常。同时原代码的列索引取值也存在错误,前两列是操作按钮,degree字段对应的单元格索引不是1。

快速修复方案

直接通过事件参数的RowIndex属性获取当前触发删除操作的行,调整代码如下:

protected void EduGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    // 用e.RowIndex获取当前删除的行,不要用SelectedRow
    GridViewRow row = EduGrid.Rows[e.RowIndex];
    conn = new SqlConnection(connString);
    string query = "DELETE FROM [Edu Info] WHERE cnic = @cnic AND degree = @degree";
    sqlcmd = new SqlCommand(query, conn);
    sqlcmd.Parameters.AddWithValue("@cnic", lblID.Text);
    // 前两列是选择、删除按钮,degree对应第3个单元格,索引为2
    sqlcmd.Parameters.AddWithValue("@degree", row.Cells[2].Text.Trim());

    try
    {
        conn.Open();
        sqlcmd.ExecuteNonQuery();
        lblInfo.Text = "Record deleted successfully.";
        lblInfo.Visible = true;
        Get_Edu();
    }
    catch (Exception ex)
    {
        lblInfo.Text = "An error occurred. Please contact the administrator.";
        lblInfo.Visible = true;
    }
    finally
    {
        conn.Close();
        conn.Dispose();
        SqlConnection.ClearAllPools();
    }
}
优化方案(推荐)

为避免后续调整列顺序导致索引取值错误,建议使用GridView的DataKeyNames属性存储业务主键字段,无需读取单元格文本:

  1. 前端GridView标签添加DataKeyNames属性:
<asp:GridView ID="EduGrid" 
    CssClass="edugrid table table-striped table-hover table-borderless" 
    runat="server" 
    AutoGenerateColumns="False" 
    GridLines="None" 
    OnRowDeleted="EduGrid_RowDeleted" 
    OnRowDeleting="EduGrid_RowDeleting"
    DataKeyNames="degree"> <!-- 新增这行,把需要用到的字段加入数据键 -->
    <!-- 其他原有内容保持不变 -->
</asp:GridView>
  1. 后端直接从数据键中取值:
// 无需读取单元格,直接从DataKeys取degree值
string degree = EduGrid.DataKeys[e.RowIndex]["degree"].ToString().Trim();
sqlcmd.Parameters.AddWithValue("@degree", degree);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:18:05