繁体   English   中英

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

[英]How to allow alphanumeric text in datagridview but exclude negative numbers

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

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

尝试像这样使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM