简体   繁体   中英

How to allow alphanumeric text in datagridview but exclude negative numbers

I'm trying to allow only alphanumeric input in my datagridview column. 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:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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