如何在datagridview中允许使用字母数字文本但排除负数

时间:2013-07-01 17:17:34

标签: vb.net validation datagridview

我正在尝试在datagridview列中仅允许使用字母数字输入。有没有办法允许字母数字输入,还可以防止用户输入负数或将单元格留空?如果有人有任何建议或答案,我将不胜感激! :)这是我的代码如下。我已经有负片和空白单元格验证工作,但它不允许我输入非数字输入。

 If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellData = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        If cellData Is Nothing OrElse IsDBNull(cellData) OrElse cellData.ToString = String.Empty Then ' This will prevent any blank cells
            MessageBox.Show("Name Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
        ElseIf cellData < 0 Then
            MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
            Exit Sub ' Again this a default value I want supplied back to the datagridivewcell 



        End If
    End If

所以我的代码有效,除非我输入任何类型的非数字字符,程序停止并退出。

1 个答案:

答案 0 :(得分:1)

尝试使用TryParse,如下所示:

    If (e.ColumnIndex = 0) Then 'checking value for column 1 only
        Dim cellValue As Integer
        If (Int32.TryParse(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value, cellValue)) Then
            If cellValue < 0 Then
                MessageBox.Show("Negative Numbers Not Allowed") 'This prevents negative numbers
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object"
                Exit Sub ' Again this a default value I want supplied back to the datagridivewcell 
            End If
        Else
            Dim testValue As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
            If (String.IsNullOrEmpty(testValue)) Then
                MessageBox.Show("Name Cannot Be Empty")
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Object" ' This is a default value that I want to supply after the message box
            End If
        End If

    End If