我的datagridview有一个组合框列,组合框有2个值。我们只是说“A”和“B”是值。
当数据加载到datagridview时,列值为空,行数无关紧要,但只有1行可以具有值“A”,只有1行可以具有值“B”。
我在CellValidating
事件中尝试了这个
If e.ColumnIndex = 5 Then
For Each row As DataGridViewRow In dg.Rows
If row.Cells(5).Value = e.FormattedValue Then
e.Cancel = True
dg.Rows(e.RowIndex).ErrorText = "Invalid Value"
Else
dg.Rows(e.RowIndex).ErrorText = ""
End If
Next
End If
我可以看到这不起作用,我的问题是我正在验证每一行,包括我正在编辑的那一行。那么我该如何正确验证呢?
答案 0 :(得分:0)
我不是在工作站测试这个。我想你应该使用Value而不是FormattedValue。您也可以尝试在CellValueChanged事件中执行此操作。 MSDN声明:Value属性是单元格包含的实际数据对象,而FormattedValue是此对象的格式化表示。
If e.ColumnIndex = 5 Then
Dim CurrValue as string = dg.rows(e.RowIndex).Cells(e.ColumnIndex).value.ToString
For Each row As DataGridViewRow In dg.Rows
If row.Cells(5).Value.ToString = CurrValue Then
e.Cancel = True
dg.Rows(e.RowIndex).ErrorText = "Invalid Value"
Else
dg.Rows(e.RowIndex).ErrorText = ""
End If
Next
End If
End Sub
答案 1 :(得分:0)
您可以创建一个函数,确认特定列没有重复值,并从CellValidating事件处理程序调用它。在这种情况下,您将调用它两次(一次用于A,一次用于B)。
Private Function DoesCellContainDuplicatedValue(ByVal intColumnToCheck As Integer, _
ByVal intCurrentRow As Integer, _
ByVal strValue As String) As Boolean
Dim bolCellContainsDuplicateValue As Boolean = False
Dim intCursor As Integer = 0
Do Until intCursor = DataGridView1.Rows.Count OrElse bolCellContainsDuplicateValue = True
'Don't check the old value for the cell we're checking.
If intCursor <> intCurrentRow AndAlso DataGridView1.Rows(intCursor).Cells(0).Value = strValue Then
bolCellContainsDuplicateValue = True
End If
intCursor += 1
Loop
Return bolCellContainsDuplicateValue
End Function
然后在你的事件处理程序中:
Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
If e.ColumnIndex = 5 AndAlso e.FormattedValue = "A" AndAlso DoesCellContainDuplicatedValue(5, e.RowIndex, "A") Then
e.Cancel = True
MsgBox("You cannot have more than one A value.")
End If
If e.ColumnIndex = 5 AndAlso e.FormattedValue = "B" AndAlso DoesCellContainDuplicatedValue(5, e.RowIndex, "B") Then
e.Cancel = True
MsgBox("You cannot have more than one B value.")
End If
End Sub