Jamie
Jamie

Reputation: 107

Totaling up a column on a Gridview and display in the footer

I am new to asp.net and I am having trouble trying to add up the itemstotal values in my shoppingcart. The code I have doesn't work but I feel like I am on the right track. Can someone help me?

ShoppingCart.aspx

<asp:TemplateField HeaderText="Item Total">
     <ItemTemplate>
        <asp:Label ID="lblItemTotal" runat="server" DataFormatString="{0:c2}"></asp:Label>
     </ItemTemplate>
     <FooterTemplate>
        <asp:Label ID="lblTotal" runat="server" Text="Order Total: "></asp:Label>
    </FooterTemplate>

ShoppingCart.aspx.cs

foreach (GridViewRow row in gvProductsList.Rows)
{
   Label lblItemTotal = (Label)row.FindControl("lblItemTotal");//find itemTotal label
   decimal decPrice = decimal.Parse(lblItemTotal.Text, NumberStyles.Currency);//convert to decimal
   decimal newtotal =+ decPrice;
   Label lblTotal = (row.FindControl("lblTotal")) as Label;
   lblTotal.Text = "$" + Convert.ToString(newtotal);
 }

I get a nullexception for the line lblTotal.Text = "$" + Convert.ToString(newtotal);

Upvotes: 2

Views: 720

Answers (1)

Alex Bariyev
Alex Bariyev

Reputation: 78

I am a newbie myself, but I think inside your foreach loop you need to either check if the row you're looking at is indeed a footer before pointing to the label inside of the footer, or, I believe, you can get your footer row with:

var footerRow = gvProductsList.FooterRow;

EDIT: I don't have VS with me right now, but try this:

decimal newtotal;
foreach (GridViewRow row in gvProductsList.Rows)
{
   Label lblItemTotal = (Label)row.FindControl("lblItemTotal");
   decimal decPrice = decimal.Parse(lblItemTotal.Text, NumberStyles.Currency); 
   newtotal =+ decPrice;
 }
 var footerRow = gvProductsList.FooterRow;
 Label lblTotal = (footerRow.FindControl("lblTotal")) as Label;
 lblTotal.Text = "$" + Convert.ToString(newtotal);

Upvotes: 2

Related Questions