Datagridview - Input string was not in a correct format

gbhs

Member
Joined
Jan 19, 2013
Messages
11
Programming Experience
Beginner
Hi
I have a datagrid with 2 columns (Scores(Int) index 0 and Comment(nchar) index 1)
Comment columnvalue depends on score value.

This code works well in my cellvaluechanged event

If e.ColumnIndex = 0 Then
If Not IsDBNull(Me.dgvStudDisc.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) Then
If Me.dgvStudDisc.Rows(e.RowIndex).Cells(e.ColumnIndex).Value >= 0 And
Me.dgvStudDisc.Rows(e.RowIndex).Cells(e.ColumnIndex).Value <= 5 Then
Me.dgvStudDisc.Rows(e.RowIndex).Cells(1).Value = "Very Poor"
Else
Me.dgvStudDisc.Rows(e.RowIndex).Cells(1).Value = DBNull.Value
End If
End If
End if

PROBLEM: when I enter a value in score column and want to delete it I get the above exception.
Can someone help me modify the code to handle this problem?
gbhs
 
Does that first column allow nulls?

By the way, don't keep using expressions like 'Me.dgvStudDisc.Rows(e.RowIndex)' and 'Me.dgvStudDisc.Rows(e.RowIndex).Cells(e.ColumnIndex).Value' over and over. Good practice dictates that you evaluate those expressions once only and assign their value to a variable and use that repeatedly, e.g.
Dim row = Me.dgvStudDisc.Rows(e.RowIndex)
Dim currentCellValue = row.Cells(e.ColumnInde x).Value
Dim nextCell = row.Cells(1)

If currentCellValue Is DBNull.Value Then
    nextCell.Value = DBNull.Value
Else
    Select Case CInt(currentCellValue)
        Case < 0
            '...
        Case < 6
            nextCell.Value = "Very Poor"
        Case Else
            '...
    End Select
End If
I assume that your data is bound too, so you might even do away with that code altogether and instead set the Expression property of the second DataColumn.
 
Back
Top