验证组合框选择



我的datagridview有一个组合框列,这个组合框有2个值。假设"A"one_answers"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

我可以看到这是如何不起作用的,我的问题是我正在验证每一行,包括我目前正在编辑的一行。那么我如何正确地验证这个呢?

我不在工作站上进行测试。我认为你应该使用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 

您可以创建一个函数来确认特定列没有重复的值,并从cellvalididating事件处理程序调用它。在本例中,您将调用它两次(一次用于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

最新更新