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

VB.NET中两个ComboBox筛选DataGridView仅单条件生效问题求解

问题根因
  • 条件判断逻辑完全错误:VB.NET中&是字符串拼接运算符,不能用作逻辑与判断,需使用AndAlso;ComboBox未选中时SelectedIndex值为-1,而非Nothing,原有判断条件全部不生效,导致分支执行顺序完全混乱,分类筛选逻辑无法正常触发。
  • 分支优先级错误:你将两个ComboBox同时选中的判断放在了最后,且该分支的SQL仅写了分类筛选条件,未加入品牌筛选,同时也会导致单个分类筛选的分支永远无法命中。
  • 冗余代码问题:BrandDisplay和CategoryDisplay方法逻辑完全重复,且每个查询都重复执行了两次ExecuteReader(),额外占用数据库资源。
修复方案

直接重构搜索逻辑,动态拼接查询条件,避免冗余代码,修正判断逻辑:

Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
    ' 先判断是否至少选中了一个筛选条件
    If CmbBrand.SelectedIndex = -1 AndAlso CmbCategory.SelectedIndex = -1 Then
        MessageBox.Show("请至少选择一个品牌或分类进行筛选", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Return
    End If

    If DbConnect() Then
        Try
            DgvRecord.Rows.Clear()
            Dim SQLCmd As New OleDbCommand
            With SQLCmd
                .Connection = cn
                ' 基础SQL
                Dim sqlStr As String = "Select * From TblStock Where 1=1 "
                ' 动态拼接筛选条件
                If CmbBrand.SelectedIndex <> -1 Then
                    sqlStr &= " And STBrand Like @BrandSearch"
                    .Parameters.AddWithValue("@BrandSearch", "%" & CmbBrand.Text.Trim() & "%")
                End If
                If CmbCategory.SelectedIndex <> -1 Then
                    sqlStr &= " And STCategory Like @CategorySearch"
                    .Parameters.AddWithValue("@CategorySearch", "%" & CmbCategory.Text.Trim() & "%")
                End If
                .CommandText = sqlStr
                ' 仅执行一次查询
                Dim rs As OleDbDataReader = .ExecuteReader()
                While rs.Read
                    Dim NewStockRow As New DataGridViewRow()
                    NewStockRow.CreateCells(DgvRecord)
                    NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
                    NewStockRow.Tag = rs("StockID")
                    DgvRecord.Rows.Add(NewStockRow)
                End While
                rs.Close()
            End With
        Catch ex As Exception
            MessageBox.Show("查询出错:" & ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            ' 确保数据库连接一定会关闭,避免连接泄漏
            cn.Close()
        End Try
    End If
End Sub

修复后可同时支持仅选品牌筛选、仅选分类筛选、同时选品牌+分类联合筛选三种场景,原有冗余的BrandDisplay和CategoryDisplay方法可直接删除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 04:15:05