0

i was trying to get the sum of the row items in a datagridview
this is my code

 Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click


    If DataGridView1.RowCount > 1 Then
        Dim RegFee As Integer = 0
        Dim MisFee As Integer = 0
        Dim TuiFee As Integer = 0
        Dim PtcaFee As Integer = 0
        Dim CompFee As Integer = 0

        For index As Integer = 0 To DataGridView1.RowCount - 1
            RegFee += Convert.ToInt32(DataGridView1.Rows(index).Cells(4).Value)
            MisFee += Convert.ToInt32(DataGridView1.Rows(index).Cells(5).Value)
            TuiFee += Convert.ToInt32(DataGridView1.Rows(index).Cells(6).Value)
            PtcaFee += Convert.ToInt32(DataGridView1.Rows(index).Cells(7).Value)
            CompFee += Convert.ToInt32(DataGridView1.Rows(index).Cells(8).Value)

        Next
        DataGridView2.Rows.Add("Registration Fee", RegFee)
        DataGridView2.Rows.Add("Miscellaneous Fee", MisFee)
        DataGridView2.Rows.Add("Tuition Fee", TuiFee)
        DataGridView2.Rows.Add("PTCA Fee", PtcaFee)
        DataGridView2.Rows.Add("Computer Fee", CompFee)

    End If
End Sub  

but i'm having an error:
Object cannot be cast from DBNull to other types.
can you help me???

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Kaye Santos
  • 45
  • 1
  • 2
  • 7

1 Answers1

1

Use IsDbNull like this:

Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click

If DataGridView1.RowCount > 1 Then
    Dim RegFee As Integer = 0
    Dim MisFee As Integer = 0
    Dim TuiFee As Integer = 0
    Dim PtcaFee As Integer = 0
    Dim CompFee As Integer = 0
    For index As Integer = 0 To DataGridView1.RowCount - 1
        RegFee += If(IsDbNull(DataGridView1.Rows(index).Cells(4).Value), 0,   Convert.ToInt32(DataGridView1.Rows(index).Cells(4).Value))
        'Do the same for the rest
    Next
    DataGridView2.Rows.Add("Registration Fee", RegFee)
    DataGridView2.Rows.Add("Miscellaneous Fee", MisFee)
    DataGridView2.Rows.Add("Tuition Fee", TuiFee)
    DataGridView2.Rows.Add("PTCA Fee", PtcaFee)
    DataGridView2.Rows.Add("Computer Fee", CompFee)
End If

End Sub  
ilans
  • 2,537
  • 1
  • 28
  • 29
  • OK. Try again. Added the `.Value` – ilans Oct 14 '14 at 13:06
  • @Steve i'm still new in programming can you give me a sample code?i will really appreciate it :) – Kaye Santos Oct 14 '14 at 13:08
  • @KayeSantos - Try again. I've added the `.Value`. This should work: `RegFee += If(IsDbNull(DataGridView1.Rows(index).Cells(4).Value), 0, Convert.ToInt32(DataGridView1.Rows(index).Cells(4).Value))` – ilans Oct 14 '14 at 13:09