Add total in VB.Net Gridview

10,768

You must use DataBound event.

Try this:

Protected Sub GV_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles GV.DataBound
    Dim Volume As Decimal = 0
    For Each r As GridViewRow In GV.Rows
        If r.RowType = DataControlRowType.DataRow Then
            Volume += Convert.ToDecimal(r.Cells(1).Text)
        End If
    Next
    GV.FooterRow.Cells(1).Text = Math.Round(Volume, 0).ToString()
End Sub
Share:
10,768
Selrac
Author by

Selrac

Updated on June 04, 2022

Comments

  • Selrac
    Selrac almost 2 years

    I can not manage to get the gridview display the total in a footer

    I've tried the following:

    <asp:GridView ID="GV" runat="server" 
        DataSourceID="SqlQuery" EmptyDataText="No data">
        <Columns>
            <asp:BoundField DataField="Weekday" FooterText=" " HeaderText="Weekday" />
            <asp:BoundField DataField="Volume" DataFormatString="{0:N0}" 
                FooterText="." HeaderText="Volume" />            
        </Columns>
     </asp:GridView>
    
    
    Protected Sub GV_rowdatabound(sender As Object, e As GridViewRowEventArgs) Handles GV.RowDataBound
        Dim Volume as integer = 0
        For Each r As GridViewRow In GV.Rows
            If r.RowType = DataControlRowType.DataRow Then
                Volume = Volume + CDec(r.Cells(1).Text)
            End If
        Next
        GV.FooterRow.Cells(1).Text = Math.Round(Volume , 0)
    End Sub
    

    This gives me an error messages:

    Object reference not set to an instance of an object

    I followed advice in the following page and I changed the code: trying to total gridview in asp

    Sub GV_WeekSumary_rowcreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        Dim Volume as integer = 0
        For Each r As GridViewRow In GV.Rows
            If r.RowType = DataControlRowType.DataRow Then
                Volume = Volume + CDec(r.Cells(1).Text)
            End If
        Next
    
        If e.Row.RowType = DataControlRowType.Footer Then
            e.Row.Cells(1).Text = Math.Round(Volume , 0)
        End If
    End Sub
    

    This does not give an error, but the footer does not show any value.

    I've tried also the following:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Volume as integer = 0
        For Each r As GridViewRow In GV.Rows
            If r.RowType = DataControlRowType.DataRow Then
                Volume = Volume + CDec(r.Cells(1).Text)
            End If
        Next
        GV.FooterRow.Cells(1).Text = Math.Round(Volume, 0)
        GV.DataBind()
    End Sub
    

    Still no value in the footer, but when I debbug it I can see that footer is assisgned the value I need. Why it is not displayed in the website?

    Any idea how I can get this to work?