如何使datagridview的全局规则不允许负,空或空输入

时间:2013-06-24 15:02:31

标签: vb.net validation datagridview

我正在寻找一种在整个datagridview中制作全局规则的方法,如果用户输入负数或将其中一个datagridviewcells留空,则消息框会告诉用户发生了无效条目。在消息框之后,我希望能够为datagridviewcell提供默认值“na”。我的datagridview使用oledataadapter连接到excel电子表格。到目前为止,我有我在MSDN上找到的代码,但是当我使用它时,我的程序没有正确编译。除了cellvalidating事件之外,我还能在其他地方使用此代码吗?如果没有,我将非常感谢有关此事的任何其他建议或想法。非常感谢!

Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
ByVal e _
As DataGridViewCellValidatingEventArgs) _
Handles dataGridView1.CellValidating

Me.dataGridView1.Rows(e.RowIndex).ErrorText = "" 
Dim newInteger As Integer 


If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return 
If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) _
    OrElse newInteger < 0 Then

    e.Cancel = True 
    Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be a non-negative integer" 

End If 

End Sub

1 个答案:

答案 0 :(得分:0)

您可以在EditingControlShowing事件...

中执行此操作
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    Try
        'remove if there is already a handler
        RemoveHandler e.Control.KeyPress, AddressOf TextNumberKeypress
        'add handler
        AddHandler e.Control.KeyPress, AddressOf TextNumberKeypress

    Catch ex As Exception
        '... 
    End Try
End Sub


Sub TextNumberKeypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
    Dim k As Byte = Asc(e.KeyChar)
    Dim s As String = "0123456789"

    If Not s.Contains(e.KeyChar) Then
        e.Handled = True        
        If Not (k = 8 Or k = 13 Or k = 1 Or k = 3 Or k = 22) Then e.Handled = True
    End If
End Sub