How to Add a Total Column to the ASP.NET ListView

A very frequently asked question about the ASP.NET ListView control is to display the sum of a column containing numeric data. In this post, I will show you how to quickly add a total's column to the ListView control. Here's how to do so by handling the ItemDataBound and PreRender event of the ListView

In your web.config, I have added a ConnectionString as shown below:


  <connectionStrings>


    <add name="NorthwindConnectionString"


         connectionString="Data Source=(local);


         Initial Catalog=Northwind;


         Integrated Security=True"


         providerName="System.Data.SqlClient"/>


  </connectionStrings>




HTML Markup


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


    <title></title>


</head>


<body>


    <form id="form1" runat="server">


    <div>


<asp:ListView ID="lvProducts" runat="server" DataSourceID="SqlDataSource1"


OnItemDataBound="lvProducts_DataBound" OnPreRender="lvProducts_PreRender"


ItemPlaceholderID="PlaceHolder1">


 <LayoutTemplate>


        <asp:Placeholder


        id="PlaceHolder1"


        runat="server" />


        Total: <asp:Label ID="lblTotal" runat="server" Text="Total"/>        


    </LayoutTemplate>


<ItemTemplate>


    <asp:Label ID="lblProductName" runat="server"


    Text='<%# Eval("ProductName") %>'/>


    <asp:Label ID="lblUnitPrice"


    Text='<%# Eval("UnitPrice") %>' runat="server"/><br />


</ItemTemplate>


</asp:ListView>


<asp:SqlDataSource ID="SqlDataSource1" runat="server"


    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"


    SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]">


</asp:SqlDataSource>


 


    </div>


    </form>


</body>


</html>




C#


double totl = 0;


 


protected void lvProducts_DataBound(object sender, ListViewItemEventArgs e)


{


    if (e.Item.ItemType == ListViewItemType.DataItem)


    {


        Label lblUP = e.Item.FindControl("lblUnitPrice") as Label;


        totl += Convert.ToDouble(lblUP.Text);


    }


}


 


protected void lvProducts_PreRender(object sender, EventArgs e)


{


    Label lblTot = this.lvProducts.FindControl("lblTotal") as Label;


    lblTot.Text = totl.ToString(); ;


}





VB.NET


    Private totl As Double = 0


 


    Protected Sub lvProducts_DataBound(ByVal sender As Object, ByVal e As ListViewItemEventArgs)


        If e.Item.ItemType = ListViewItemType.DataItem Then


            Dim lblUP As Label = TryCast(e.Item.FindControl("lblUnitPrice"), Label)


            totl += Convert.ToDouble(lblUP.Text)


        End If


    End Sub


 


    Protected Sub lvProducts_PreRender(ByVal sender As Object, ByVal e As EventArgs)


        Dim lblTot As Label = TryCast(Me.lvProducts.FindControl("lblTotal"), Label)


        lblTot.Text = totl.ToString()


 


    End Sub







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Anonymous said...

Nice article.

I am getting the error "object not set an instance of object" for the following code: lblTot.Text = totl.tostring()

I believe tot1.tostring() is causing the error. I can see that tot1 has a sum of the rows.

Am I missing something?
Thanks,
hutty

Anonymous said...

Ok..I got it to work when I apply code to my original project and not the Northwind example.

What's the most efficient way to do multiple columns? The code works for the first column, but I need the other 11 columns to calculate as well.

I can copy the code twelve times, which I think is tedious.

Thanks,
Hutty

Anand Manmohan Bohra said...

How come you got
protected void lvProducts_DataBound(object sender, ListViewItemEventArgs e)

in my ASP project in listview Databound has this signature

protected void LVShipment_DataBound(object sender, EventArgs e)

Siki said...

create datapager and label in listview and write the below code in C# after listview1.databind();
DataPager dp = ((DataPager)lvArrivalStatus.FindControl("dpArrivalStatusTop"));
lblArrivalCount.Text = Convert.ToString(dp.TotalRowCount);

Mike Guerra said...

Nice Article Format!