vb.net 如何限制datagridview中的非数字输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17455651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:08:09  来源:igfitidea点击:

How to restrict non-numeric input in datagridview

vb.netvalidationdatagridviewrestriction

提问by stackexchange12

I'm hoping to find out a way to restrict a user from entering any non-numeric input into my datagridviewcolumn. Also I have already restricted the user from entering any negative numbers and from leaving the cell blank. If anyone can find a way to restrict the user from entering letters and non-numeric input I would greatly appreciate it!

我希望找到一种方法来限制用户在我的 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

采纳答案by Dave H

Give this a try. If you use the DataGridView.KeyPress event to monitor what was just typed, you can check what that character is with Char.IsDigit(e.KeyChar).

试试这个。如果您使用 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

回答by TrustedInSci

You can always use Integer.TryParse().

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

You can read more about it here: http://msdn.microsoft.com/en-us/library/f02979c7.aspx

您可以在此处阅读更多相关信息:http: //msdn.microsoft.com/en-us/library/f02979c7.aspx