0

我试图在我的 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

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

4

1 回答 1

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
于 2013-07-01T18:07:27.603 回答