当`datagridview`中的值重复时,防止进入下一行

时间:2018-10-25 00:46:01

标签: vb.net

我有datagrid用户将只在一列中添加值,并且我想防止此列中的数据重复,我已经通过下面的代码进行了管理,

我想要的是将选择(焦点)保留在同一编辑单元格(x)中 如果输入的数据重复,那么我尝试获取当前行索引,如果数据重复但无法正常工作,则返回该行索引。

row_index = DataGridView1.CurrentRow.Index.ToString()

Dim cell As DataGridViewCell = DataGridView1.Rows(row_index).Cells(1)
DataGridView1.CurrentCell = cell
DataGridView1.BeginEdit(True)

注意:用户将添加条形码编号,因此他将使用条形码扫描仪或手动添加条形码,然后按Enter键。

Private Sub DataGridView1_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.RowValidated
    If DataGridView1.Rows.Count > 2 Then
        Dim i As Integer = 0
        Dim row_index As Integer
        ' loop condition will loop while the row count is less or equal to i
        While i <= DataGridView1.Rows.Count - 1
            Dim j As Integer = 1

            ' loop condition will loop while the row count is less or equal to j
            While j <= DataGridView1.Rows.Count - 1
                Dim str As String = DataGridView1.Rows(i).Cells(1).Value()
                Dim str1 As String = DataGridView1.Rows(j).Cells(1).Value()

                If Not str1 = "" AndAlso Not str = "" Then
                    If str1 = str Then
                        'row_index = DataGridView1.SelectedCells.Item(i).RowIndex.ToString()
                        row_index = DataGridView1.CurrentRow.Index.ToString()

                        Dim cell As DataGridViewCell = DataGridView1.Rows(row_index).Cells(1)
                        DataGridView1.CurrentCell = cell
                        DataGridView1.BeginEdit(True)

                        Exit Sub
                    End If

                End If


                j += 1

            End While

            i += 1
        End While

    End If
End Sub

2 个答案:

答案 0 :(得分:1)

您也可以在for循环中尝试它。这就是我的方法。如果您的意思是停止/保留选择(焦点),或者只要它与您当前的数据重复,就进入一个单元格/行。这应该工作正常。

enter code here

For i = 0 To Datagridview1.Rows.Count - 1
    If Datagridview1.Rows(i).Cells(1).Value = DataYouWillInput Then
        DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(1)
        Exit for
   End If    
Next

enter code here

答案 1 :(得分:0)

如果您的条件在当前数据和您要添加的数据的条件下返回true。退出循环即可。使用这个。

DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(1)