无法将对象从DBNull强制转换为其他类型

时间:2014-10-14 12:06:09

标签: mysql vb.net

我试图获取datagridview中行项的总和 这是我的代码

 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  

但我有一个错误:
无法将对象从DBNull强制转换为其他类型 你能帮助我吗???

1 个答案:

答案 0 :(得分:1)

像这样使用IsDbNull

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