2013-11-27 66 views
2

我有一個DataGridView我的窗體之一,用戶可以編輯,然後更新,以便對其鏈接到的數據庫進行更改。爲此,我不希望任何單元格留空。目前我使用此代碼:在datagridview中停止空白單元格 - VB.NET

If datagrdSnippets.Item(e.ColumnIndex, e.RowIndex).Value Is Nothing Then 
     ' Show the user a message 
     MsgBox("Please ensure the cell has been given a value") 

     ' Fail validation (prevent them from leaving the cell) 
     e.Cancel = True 
    End If 

在DSG的小區來驗證屬性,但是當我編輯一個單元格,讓它空白什麼也沒有發生。我的代碼中是否有錯誤,或者是否需要使用其他方法?

請注意:這是在VB.NET中,我目前正在使用CellValidating事件。

謝謝:)

回答

2

Value不在CellValidating Event,但e.FormattedValue要檢查的屬性。您在代碼中使用的Value屬性不會反映當前的單元格值,而是最後一個經過驗證的單元格值。示例代碼:

Private Sub datagrdSnippets_CellValidating(sender As System.Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles datagrdSnippets.CellValidating 

    If (e.FormattedValue = "Value I want to avoid") Then e.Cancel = True 

End Sub 

請注意,此事件被稱爲不僅僅是當用戶輸入一個值,因而更多的是MsgBox「不受任何限制」不應該放在這裏(你必須設置的東西(布爾標誌,例如)確保用戶是引發這種方法的人)。

+0

拯救生命!一直被困在這一整個上午,謝謝:) –

+0

@CharlieStuart歡迎您!如果您沒有其他疑問,請將其標記爲正確的答案。 – varocarbas

相關問題