質問

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