Вопрос

I'm trying to validate a users data in a datagridview. Right now I have a column that needs to show an error message if left blank by the user. I've figured out how to show an error message if the datagridview cell is expecting a number but the user types a string. So how can I change this code to show an error message if the user leaves a datagridview cell blank.

    If (e.ColumnIndex = 0) Then 'checking numeric value for column 1 only
       Dim value As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString()
       For Each c As Char In value
           If Not Char.IsDigit(c) Then
               MessageBox.Show("Please Enter numeric Value")
               DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = String.Empty
               Exit Sub
            End If
        Next
    End If
Это было полезно?

Решение

If there is the possibility that the cell is Nothing, do not try to apply the ToString(), instead assign the Value property and then test against Nothing and then using the OrElse operator against an empty string

If (e.ColumnIndex = 0) Then 'checking numeric 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
       MessageBox.Show("Please Enter a Value")
       Exit Sub
   End If

   Dim value = cellData.ToString()
   For Each c As Char In value
      ......
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top