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

ASP.NET查询数据库无匹配行时给TextBox赋值0失效报错问题

错误原因

  • 当数据库不存在匹配的KdNota记录时,查询返回的结果集是空的,DataTable dt的Rows集合行数为0,直接访问dt.Rows[0]就会触发"There is no row at position 0"异常。
  • 你写的ISNULL(KdNota, 0)只有在存在匹配行、但KdNota字段值为NULL的时候才会生效,结果集为空的场景下这个函数不会执行,完全起不到预期作用。
  • 你给查询结果取了别名vKdNota,但else分支取值用的是原字段名KdNota,就算查询返回了行,也会触发找不到对应列的异常。
  • 原有代码采用字符串拼接SQL,存在SQL注入风险,需要优化。

修复方案

核心逻辑调整

先判断DataTable是否存在返回行,无返回行直接用默认值"0"即可,不需要强行访问空行的数据。同时推荐改成参数化查询避免注入风险。

修复后完整代码

protected void CheckNota()
{
    string vNota = "0"; // 先默认赋值为0,无匹配行直接用该值
    using (SqlConnection con = new SqlConnection(constr))
    {
        // 改为参数化查询,避免SQL注入
        using (SqlCommand cmd1 = new SqlCommand("select KdNota from tProdukBeliHead where KdNota = @KdNota", con))
        {
            cmd1.Parameters.AddWithValue("@KdNota", txtKdBeli.Text.Trim());
            using (SqlDataAdapter da = new SqlDataAdapter(cmd1))
            {
                DataTable dt = new DataTable();
                da.Fill(dt);
                // 存在行时再读取字段值
                if (dt.Rows.Count > 0)
                {
                    // 兼容字段值为NULL的场景
                    vNota = dt.Rows[0]["KdNota"] == DBNull.Value ? "0" : dt.Rows[0]["KdNota"].ToString();
                }
            }
        }
    }
    // 给你的目标TextBox赋值,替换为你实际的控件ID即可
    txt目标控件ID.Text = vNota;
}

更简化的实现(不需要DataTable)

如果只需要判断是否存在匹配值,可以用ExecuteScalar减少不必要的资源开销:

protected void CheckNota()
{
    string vNota = "0";
    using (SqlConnection con = new SqlConnection(constr))
    {
        con.Open();
        using (SqlCommand cmd1 = new SqlCommand("select KdNota from tProdukBeliHead where KdNota = @KdNota", con))
        {
            cmd1.Parameters.AddWithValue("@KdNota", txtKdBeli.Text.Trim());
            object result = cmd1.ExecuteScalar();
            if (result != null && result != DBNull.Value)
            {
                vNota = result.ToString();
            }
        }
    }
    txt目标控件ID.Text = vNota;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:45:07