I am having problems when validating the data entered in a datagridview, even if I enter a different code this validates it for me.
With this code I search for the product or data that is shown in the datagrid view
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)
For Each data As DataRow In dt.Rows
'Dim aa As Integer = Me.dgvdetalle.Rows.Add()
' Me.dgvproductoscanjes.Rows(aa).Cells(0).Value = data("seleccionar").ToString().Trim
Me.dgvdetalle.CurrentRow.Cells(0).Value = data("IDPRODUCTO").ToString()
Me.dgvdetalle.CurrentRow.Cells(1).Value = data("DESCRIPCION").ToString()
Next
End Sub
And with this code in the CellEndEdit datagridview event I do the validation.
Private Sub dgvdetalle_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvdetalle.CellEndEdit
Dim clave As String
Dim nlinea As Integer
Select e.ColumnIndex
Case 0
clave = dgvdetalle.Rows(dgvdetalle.CurrentRow.Index).Cells(0).Value
nlinea = dgvdetalle.CurrentRow.Index
For i As Integer = 0 To dgvdetalle.Rows.Count - 1
If clave = dgvdetalle.Rows(dgvdetalle.CurrentRow.Index).Cells(0).Value And i <> nlinea Then
dgvdetalle.Rows(nlinea).Cells(0).Value = ""
MsgBox("esta repetido el codigo")
SendKeys.Send("{UP}")
Exit Sub
End If
Next
End Select
End Sub
CodePudding user response:
Your problem is with this line If clave = dgvdetalle.Rows(dgvdetalle.CurrentRow.Index).Cells(0).Value And i <> nlinea Then
clave will always be equal to dgvdetalle.Rows(dgvdetalle.CurrentRow.Index).Cells(0).Value because that is what you assigned to it. The loop is not changing the current row, it is only changing the value of i.
You want to compare clave to dgvdetalle.Rows(i).Cells(0).Value.ToString.
The ToString is necessary with Option Strict On which it should be. Turn it on in Project Properties on the Compile tab and in the Tools menu -> Options -> Projects and Solutions -> VB Defaults.
I changed the Select Case to an If since there was only a single case.
Private Sub dgvdetalle_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvdetalle.CellEndEdit
Dim clave As String
Dim nlinea As Integer
If e.ColumnIndex = 0 Then
clave = dgvdetalle.Rows(dgvdetalle.CurrentRow.Index).Cells(0).Value.ToString
nlinea = dgvdetalle.CurrentRow.Index
For i As Integer = 0 To dgvdetalle.Rows.Count - 1
If clave = dgvdetalle.Rows(i).Cells(0).Value.ToString And i <> nlinea Then
dgvdetalle.Rows(nlinea).Cells(0).Value = ""
MsgBox("esta repetido el codigo")
SendKeys.Send("{UP}")
Exit Sub
End If
Next
End If
End Sub

