簡體   English   中英

DataGridView驗證組合框選擇

[英]DataGridView Validating combobox selection

我的datagridview有一個combobox列,combobox有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

我可以看到這是行不通的,我的問題是我正在驗證包括我當前正在編輯的每一行。 那么我該如何正確驗證呢?

我不在工作站上對此進行測試。 我認為您應該使用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 

您可以創建一個函數來確認特定列沒有重復的值,然后從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM