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

VB.NET DataGridView重复数据校验逻辑不一致问题咨询

问题排查及修复方案

根本错误原因

你编写的重复校验逻辑存在语法逻辑错误:循环遍历行时,始终拿输入值和当前编辑行的第一列值做比较,等式两边永远相等,只要存在其他行(i不等于当前行号)就会触发重复判定,这是你所有输入都会被误判为重复的核心原因。

其他潜在问题

  • 取值未做空值校验和格式统一:单元格值为空时直接赋值给字符串变量会触发空引用异常,且未做Trim处理、未统一编码比较规则,可能会出现空格、编码差异导致的校验异常
  • KeyUp事件逻辑缺陷:如果产品查询接口返回多条数据,循环会反复覆盖当前行的内容,最终只会保留查询结果最后一条的产品信息
  • SendKeys操作不稳定:依赖系统焦点的SendKeys方法容易出现定位偏差,建议直接通过控件属性控制单元格选中状态

修复后代码

重复校验逻辑(CellEndEdit事件)

Private Sub dgvdetalle_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellEndEdit
    ' 仅校验第一列输入
    If e.ColumnIndex <> 0 Then Exit Sub
    
    Dim currentRowIndex As Integer = e.RowIndex
    Dim currentCellValue = dgvdetalle.Rows(currentRowIndex).Cells(0).Value
    ' 空值跳过校验
    If currentCellValue Is Nothing OrElse String.IsNullOrWhiteSpace(currentCellValue.ToString()) Then Exit Sub
    
    Dim clave As String = currentCellValue.ToString().Trim()
    
    ' 遍历行做重复校验
    For i As Integer = 0 To dgvdetalle.Rows.Count - 1
        ' 跳过当前行和空白新增行
        If i = currentRowIndex OrElse dgvdetalle.Rows(i).IsNewRow Then Continue For
        
        Dim compareValue = dgvdetalle.Rows(i).Cells(0).Value
        If compareValue Is Nothing Then Continue For
        
        Dim compareStr As String = compareValue.ToString().Trim()
        ' 采用序号比较规则,避免不同文化、编码差异导致的误判
        If String.Equals(clave, compareStr, StringComparison.Ordinal) Then
            dgvdetalle.Rows(currentRowIndex).Cells(0).Value = ""
            MsgBox("esta repetido el codigo")
            ' 直接定位到当前编辑单元格,替代不稳定的SendKeys
            dgvdetalle.CurrentCell = dgvdetalle.Rows(currentRowIndex).Cells(0)
            dgvdetalle.BeginEdit(True)
            Exit Sub
        End If
    Next
End Sub

KeyUp事件优化建议

如果查询产品默认取第一条匹配结果,可删除循环直接取第一行数据,避免无效覆盖:

Private Sub dgvdetalle_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvdetalle.KeyUp
    dt = negLog.buscar_pro_parametro(VGlobales.Base, Me.dgvdetalle.CurrentRow.Cells(0).Value)
    ' 仅在查询有结果时赋值
    If dt IsNot Nothing AndAlso dt.Rows.Count > 0 Then
        Dim data As DataRow = dt.Rows(0)
        Me.dgvdetalle.CurrentRow.Cells(0).Value = data("IDPRODUCTO").ToString()
        Me.dgvdetalle.CurrentRow.Cells(1).Value = data("DESCRIPCION").ToString()
    End If
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:09:05