VB.NET GridView忽略页脚总计中的空值

时间:2014-02-10 15:33:29

标签: asp.net vb.net dataview

VB.net

Protected Sub monthlyReportsUK_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then
   Dim rowTotal As Decimal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString)
   grdTotal = grdTotal + rowTotal
End If

If e.Row.RowType = DataControlRowType.Footer Then
   Dim lbl As Label = DirectCast(e.Row.FindControl("lblwebsVal"), Label)
   lbl.Text = "£" + grdTotal.ToString("##,0.00")
End If

End Sub

HTML:

<asp:TemplateField HeaderText="webShopTotal">
<ItemTemplate>
    <asp:Label ID="lblamount" runat="Server" Text='<%# Eval("webShopTotal") %>' />
</ItemTemplate>
<FooterTemplate>
    <asp:Label ID="lblwebsVal" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>

GridView的

Month   Value
Jan     NULL
Feb     NULL
Mar     15.00
Apr     10.00

我希望能够对这些值求和:

   Month   Value
    Jan     NULL
    Feb     NULL
    Mar     15.00
    Apr     10.00
   Total    25.00

但是,我收到错误Object cannot be cast from DBNull to other types.

有什么办法可以在页脚中添加忽略NULL值的总数吗?

1 个答案:

答案 0 :(得分:0)

试试这个

Protected Sub monthlyReportsUK_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then    
 If DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString IsNot Nothing AndAlso DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString IsNot DbNull.Value Then
   Dim rowTotal As Decimal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString)
   grdTotal = grdTotal + rowTotal
 End Id
End If

If e.Row.RowType = DataControlRowType.Footer Then
   Dim lbl As Label = DirectCast(e.Row.FindControl("lblwebsVal"), Label)
   lbl.Text = "£" + grdTotal.ToString("##,0.00")
End If

End Sub

修改

首先,您应该始终使用System.Decimal.TryParse()而不是Convert.ToDecimal()

Dim result  = 0
Dim rowTotal As Decimal = Decimal.TryParse(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString), out result)