[英]How to allow alphanumeric text in datagridview but exclude negative numbers
I'm trying to allow only alphanumeric input in my datagridview column. 我试图只允许在我的datagridview列中输入字母数字。 Is there a way to allow alphanumeric input and also prevent the user from entering negative numbers or leaving the cell blank? 有没有一种方法可以允许字母数字输入并且还可以防止用户输入负数或将单元格留空? If anyone has any suggestions or answers I would greatly appreciate it! 如果有人有任何建议或答案,我将不胜感激! :) Here is my code below. :)这是我的下面代码。 I already have the negative and blank cell validation working, but its not allowing me to input non-numeric input. 我已经可以使用否定和空白单元格验证了,但是它不允许我输入非数字输入。
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
So my code works, except when I enter any type of non-numeric character the program stops and exits. 因此,我的代码可以工作,除非输入任何类型的非数字字符,程序都会停止并退出。
Try using TryParse
like this: 尝试像这样使用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.