DataTable DBNull行值错误

时间:2014-03-20 18:45:19

标签: datagridview datagrid vb.net-2010 datarow datacolumn

在引用数据行中的项目时遇到问题。

当我执行下面的代码时,我的目的是将数据网格视图传输到数据表,与数据进行比较并执行一组特定的事件,但是当我运行

每个PaymentRow作为DataRow在dtPayments.Rows

我发现行中的所有项目都是“DBNull”。

代码在以下行中断

“如果PaymentRow.Item(”Amount“)= PaymentRow.Item(”OutstandingBalance“)则”

由于它无法比较两个DBNull对象而导致的错误

我坚持这个,因为我已经无数次地审查了我的代码,但仍然无法深究它。

提前感谢帮助人员

 Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
    Dim dtPayments As New DataTable

    For Each dgColumn As DataGridViewColumn In dgvInvoices.Columns
        Dim dc As New DataColumn
        dc.ColumnName = dgColumn.Name
        dc.DataType = dgColumn.ValueType
        dtPayments.Columns.Add(dc)
    Next

    For Each dgRow As DataGridViewRow In dgvInvoices.Rows

        Dim drow As DataRow = dtPayments.NewRow
        For Each dCell As DataGridViewCell In dgRow.Cells
            If dCell.OwningColumn.Name = "Amount" Then
                If IsDBNull(dCell.Value) Then
                    drow.Item(dCell.OwningColumn.Name) = 0.0
                Else
                    drow.Item(dCell.OwningColumn.Name) = dCell.Value
                End If
            Else
                drow.Item(dCell.OwningColumn.Name) = dCell.Value
            End If
        Next

        dtPayments.Rows.Add(dgRow)


    Next


    For Each PaymentRow As DataRow In dtPayments.Rows

        Dim strInvoiceRef As String = PaymentRow.Item("InvoiceRef").ToString


        If PaymentRow.Item("Amount") = PaymentRow.Item("OutstandingBalance") Then
            CreateDebit(PaymentRow.Item("Amount"), strInvoiceRef)
            CropTrackMod.PaidInvoiceHeader(strInvoiceRef, True)
            Dim dtTicketsOnInvoice As DataTable = CropTrackMod.GetDistinctTicketsOnInvoice(strInvoiceRef)
            For Each DistinctRow As DataRow In dtTicketsOnInvoice.Rows
                'set this list to paid
                CropTrackMod.PaidTicket(DistinctRow.Item("TicketRef").ToString(), True)

            Next
        ElseIf PaymentRow.Item("AmountPaid") < PaymentRow.Item("OutstandingBalance") Then
            CreateDebit(PaymentRow.Item("Amount"), strInvoiceRef)
        End If


    Next

End Sub

1 个答案:

答案 0 :(得分:0)

除了检查&#34;金额&#34;,还要检查&#34; OutstandingBalance&#34;循环遍历行时是DBNull。这样它也将被设置为0.0,因此您之后的比较是有效的:

For Each dgRow As DataGridViewRow In dgvInvoices.Rows
        Dim drow As DataRow = dtPayments.NewRow
        For Each dCell As DataGridViewCell In dgRow.Cells
            If dCell.OwningColumn.Name = "Amount" Or dCell.OwningColumn.Name = "OutstandingBalance" Then
                etc.