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

C#搜索功能文本框异常,调用存储过程填充DataGridView结果不正确

问题原因与修复方案

已确认的错误点

  • 连接对象使用错误:using块中已经打开了SqlConnection con,但初始化SqlCommand时又调用了一次db.Connect()创建新连接,新连接未被托管也大概率未打开,执行查询时的报错被空catch块吞掉无提示。
  • 参数类型不匹配:存储过程中@Itemcode定义为char(15)定长类型,传入带%通配符的字符串时会自动补空格到15位,导致LIKE匹配逻辑失效,无法查询到正确结果。
  • 异常被吞:空的catch (Exception ex) {}块会吃掉所有运行错误(连接错误、参数错误、权限问题等),无法感知代码执行异常。
  • 部分场景缺参数:当activeform.formname为"Issuance List"时,@WHSE参数的赋值代码被注释,此时@WHSE为空字符串,查询条件A.whsecode = @WHSE永远不成立,无返回结果。

修复步骤

第一步:修改存储过程参数类型

将存储过程的定长参数改为可变长,避免自动补空格的问题:

ALTER PROCEDURE [dbo].[sp_WhseItemsList] 
    @Action char(5) = '',
    @WHSE varchar(15) = '', -- 从char改为varchar
    @Desc varchar(50) = '',
    @Itemcode varchar(30) = '' -- 从char(15)改为更长的varchar,预留通配符位置
AS
BEGIN
    SET NOCOUNT ON;
    -- 原有查询逻辑保持不变
    IF @Action = 'A'
        BEGIN
            SELECT DISTINCT A.*, B.description, B.uom 
            FROM inventoryTable A  
            LEFT OUTER JOIN Items B 
            ON A.itemcode = B.itemcode WHERE A.whsecode = @WHSE;
        END

    IF @Action = 'I'
        BEGIN
            SELECT DISTINCT A.*, B.description, B.uom 
            FROM inventoryTable A  
            LEFT OUTER JOIN Items B 
            ON A.itemcode = B.itemcode WHERE (A.whsecode = @WHSE) AND (A.itemcode LIKE @Itemcode);
        END

    IF @Action = 'D'
        BEGIN
            SELECT DISTINCT A.*, B.description, B.uom 
            FROM inventoryTable A  
            LEFT OUTER JOIN Items B 
            ON A.itemcode = B.itemcode WHERE (A.whsecode = @WHSE) AND (B.description LIKE @Desc);
        END
END

第二步:修改C#业务代码

修复连接使用、异常捕获、参数缺失问题:

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    if (txtSearch.Text == "")
    {
        DGViewListItems.Rows.Clear();
        populateTable();
    }
    else
    {
        if (byItemcode.Checked == true)
        {
            DGViewListItems.Rows.Clear();
            using (SqlConnection con = db.Connect())
            {
                try
                {
                    SqlDataReader rd;
                    // 改用using块中已创建的con连接,避免重复开连接
                    SqlCommand cmd = new SqlCommand("sp_WhseItemsList", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@Action", "I");
                    switch (activeform.formname)
                    {
                        case "Issuance List":
                            // 恢复被注释的WHSE参数赋值
                            cmd.Parameters.AddWithValue("@WHSE", STEntry.whseFr.Text.Trim());
                            break;
                        case "Stocks Transfer List":
                            cmd.Parameters.AddWithValue("@WHSE", STEntry.whseFr.Text.Trim());
                            break;
                        case "Stocks Adjustment List":
                            cmd.Parameters.AddWithValue("@WHSE", SADJEntry.txtWhse.Text.Trim());
                            break;
                    }
                    cmd.Parameters.AddWithValue("@Desc", "");
                    cmd.Parameters.AddWithValue("@Itemcode", '%' + txtSearch.Text.Trim() + '%');
                    rd = cmd.ExecuteReader();
                    int i = 0;
                    if (rd.HasRows)
                    {
                        while (rd.Read())
                        {
                            DGViewListItems.Rows.Add();
                            DGViewListItems.Rows[i].Cells["itemcode"].Value = rd["itemcode"].ToString();
                            DGViewListItems.Rows[i].Cells["whsecode"].Value = rd["whsecode"].ToString();
                            DGViewListItems.Rows[i].Cells["description"].Value = rd["description"].ToString();
                            DGViewListItems.Rows[i].Cells["uom"].Value = rd["uom"].ToString();
                            DGViewListItems.Rows[i].Cells["quantity"].Value = rd["quantity"].ToString();
                            i++;
                        }
                    }
                    rd.Close(); // 手动释放DataReader资源
                }
                catch (Exception ex)
                {
                    // 保留异常提示,方便后续排查问题
                    MessageBox.Show("查询出错:" + ex.Message);
                }
            }
        }
        else if (byDescription.Checked == true)
        {
            // 后续补充按描述搜索的逻辑即可
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:36:08