我是 ASP.NET 新手,在尝试添加购物车中的商品总值(value)时遇到困难。我的代码不起作用,但我觉得我走在正确的轨道上。有人可以帮助我吗?
购物车.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);
}
我得到了该行的空异常 lblTotal.Text = "$"+ Convert.ToString(newtotal);
最佳答案
我自己是个新手,但我认为在 foreach 循环中,您需要在指向页脚内的标签之前检查您正在查看的行是否确实是页脚,或者,我相信,您可以获取页脚行:
var footerRow = gvProductsList.FooterRow;
编辑: 我现在没有 VS,但试试这个:
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);
关于c# - 总计 Gridview 上的列并显示在页脚中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37444572/