vb.net DataGridView 中整数的输入验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17180310/
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 13:57:50  来源:igfitidea点击:

Input Validation for an integer in DataGridView

vb.netparsingvalidationdatagridview

提问by stackexchange12

I'm able to use the code below to check whether or not a user inputs a string in a datagridview cell. If the user inputs a string a message pops up to tell them "only numeric entries are allowed". This is exactly what I want my code to do. However if I try to use this code in a column of data populated with numbers I get an error message that says "error happened, parsing commit". If anyone is able to figure out what the issue is here I would greatly appreciate it!

我可以使用下面的代码来检查用户是否在 datagridview 单元格中输入了字符串。如果用户输入一个字符串,则会弹出一条消息,告诉他们“只允许输入数字”。这正是我想要我的代码做的事情。但是,如果我尝试在填充有数字的数据列中使用此代码,则会收到一条错误消息,指出“发生错误,解析提交”。如果有人能够弄清楚这里的问题是什么,我将不胜感激!

If (e.ColumnIndex = 3) Then 'checking numeric value for column 3 only
        Dim value As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        For Each c As Char In value
            If Not Char.IsDigit(c) Then
                MessageBox.Show("Please Enter numeric Value")
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 3 'This will set the defaultvalue of the datagrid cell in question to the value of "3"
                Exit Sub
            End If
        Next
    End If

回答by stackexchange12

This solution not only checks for non-integer values it also works for every column populated with numbers for the entire datagridview. Also if the user inputs a non-integer if will supply a default value for the datagridviewcell, this default value is the previous number.

此解决方案不仅检查非整数值,它还适用于填充了整个 datagridview 的数字的每一列。此外,如果用户输入非整数 if 将为 datagridviewcell 提供默认值,则此默认值是前一个数字。

Private Sub DataGridView1_DataError(ByVal sender As Object, _
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError

    If StrComp(e.Exception.Message, "Input string was not in a correct format.") = 0 Then
        MessageBox.Show("Please Enter a numeric Value") 
        'This will change the number back to original
        DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = " "
    End If




End Sub

回答by matzone

Do this in cellvalidating event ...

在 cellvalidating 事件中执行此操作...

If (e.ColumnIndex = 3) Then 'checking numeric value for column 3 only

    If Not Isnumeric(e.Formatted.Value) Then

        MessageBox.Show("Please Enter numeric Value")
        DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 3 'This will set the defaultvalue of the datagrid cell in question to the value of "3"
        Exit Sub

    End If

End If