用戶輸入幾個值,我需要拿出一個辦法來限制我的DGV進入一列比1
或2
任何其他用戶。我擁有它,因此用戶只能輸入一個號碼,但我需要進一步的限制才能符合FOREIGN KEY
的限制條件。如何限制在一個DataGridView
任何想法?
當前驗證到位:
Private Sub dgvCategories_EditingControlShowing(ByVal sender As Object, _
ByVal e As DataGridViewEditingControlShowingEventArgs) _
Handles dgvCategories.EditingControlShowing
CType(Me.dgvCategories.Columns(0), DataGridViewTextBoxColumn).MaxInputLength = 50
CType(Me.dgvCategories.Columns(1), DataGridViewTextBoxColumn).MaxInputLength = 1
End Sub
Private Sub dgvCategories_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles dgvCategories.DataError
If StrComp(e.Exception.Message, "Input string was not in a correct format.") = 0 Then
MessageBox.Show("Please Enter either 1 (Expense) or 2 (Income) in the Transaction Type column.")
'This will change the number back to original
dgvCategories.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = " "
End If
End Sub
與解決方案圍繞播放:
Dim CurValue As Integer
Private Sub dgvCategories_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgvCategories.CellEnter
CurValue = dgvCategories.Rows.Item(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
Private Sub dgvCategories_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvCategories.CellEndEdit
Dim NewValue As Integer = dgvCategories.Rows.Item(e.RowIndex).Cells(e.ColumnIndex).Value
If NewValue < 1 Or NewValue > 2 Then
dgvCategories.Rows.Item(e.RowIndex).Cells(e.ColumnIndex).Value = CurValue
End If
End Sub
我得到這個錯誤:Conversion from string "Unassigned" to type 'Integer' is not valid.
這我假設是從該NULL
項datagridview的「新行」。
如何修改這個解決方案的任何猜測?
編輯:感謝夜間,我改變了我的邏輯是:
Private Function CleanInputNumber(ByVal str As String) As String
Return System.Text.RegularExpressions.Regex.Replace(str, "[03456789]", "1")
End Function
Private Sub xDataGridView_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
If DataGridView1.CurrentRow.Cells("ColumnType").IsInEditMode Then
Dim c As Control = DataGridView1.EditingControl
Select Case DataGridView1.Columns(e.ColumnIndex).Name
Case "ColumnType"
c.Text = CleanInputNumber(c.Text)
End Select
End If
End Sub
就像一個魅力!
安置自己的代碼,強制數字 – rheitzman
好吧,編輯OP。 – Sev09
我建議你繼續玩'CellValueChanged'事件。此代碼:'如果e.ColumnIndex> = 0 AndAlso e.RowIndex> = 0 Then dgvCategories(e.ColumnIndex,e.RowIndex).Value =「5」 End If' 會將第一列中的任何輸入轉換爲「5」(使用此事件時,務必確保列/行大於或等於0)。您可以根據您希望的方法構建複雜的條件並更改給定的單元格值。 – varocarbas