如何在datagridview中限制非数字输入

时间:2013-07-03 18:32:39

标签: vb.net validation datagridview restriction

我希望找到一种方法来限制用户输入我的datagridviewcolumn中的任何非数字输入。此外,我已经限制用户输入任何负数并将单元格留空。如果有人能找到限制用户输入字母和非数字输入的方法,我将非常感激!

If (e.ColumnIndex = 8) Then 'This specifies the column number
        Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then
            MessageBox.Show("Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0
        ElseIf cellData < 0 Then
            MessageBox.Show("Negatives Values Not Allowed")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 0

            Exit Sub

        End If
    End If

2 个答案:

答案 0 :(得分:2)

您始终可以使用Integer.TryParse()

您可以在此处详细了解:http://msdn.microsoft.com/en-us/library/f02979c7.aspx

答案 1 :(得分:1)

试一试。如果您使用DataGridView.KeyPress事件来监视刚刚输入的内容,则可以使用Char.IsDigit(e.KeyChar)检查该字符的内容。

Private Sub DataGridView1_KeyPress(sender As Object, e As     System.Windows.Forms.KeyPressEventArgs) Handles DataGridView1.KeyPress
    If (Char.IsDigit(e.KeyChar)) Then
        'this is a number
    Else
        'not a number
    End If
End Sub
相关问题