ItemTemplate中的.Net String.Format货币与Databound中的小计

时间:2012-06-28 14:38:47

标签: .net listview currency itemtemplate string.format

我有一个显示购物车的ListView。它工作正常,直到我添加String.Format以将LineTotal十进制显示为货币字符串。当我在LineTotal上有一个Eval时,它正在工作。

当我添加String.Format时会出现问题 - 它会混淆代码隐藏。错误:输入字符串的格式不正确。

在C#中,我获取文本标签的值,并在整个代码隐藏中使用它来完成诸如累加产品总值(sum var)之类的事情。

我希望PriceLabel价格显示为货币,但也可以在我的Listview数据绑定函数中使用标签的值,以便我可以更新sum var。

缩写项目模板:

<ItemTemplate>               
<asp:Label ID="PriceLabel" runat="server" Text='<%# String.Format("{0:C}", Eval("LineTotal"))%>' ></asp:Label>
</ItemTemplate>

代码隐藏:

    protected void ProductListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
        if (e.Item.ItemType == ListViewItemType.DataItem)
            {
            //update subtotal by finding the label string value
            Label lbl = (Label)e.Item.FindControl("PriceLabel") as Label;

            decimal sublinetotal = Convert.ToDecimal(lbl.Text);// <---- Input error here

            //update the sum var to show the total price on the page
            sum += sublinetotal;

            }
        }

1 个答案:

答案 0 :(得分:2)

我认为在这种情况下你的方法并不是很好。

首先,你得到的错误是因为lbl.Text可能是空的,因为正在进行绑定(参见,ASPX文件中的值将在ItemDataBound事件之后设置)。因此,您最好直接设置读取DataItem:

var row = e.Item.DataItem as System.Data.DataRowView;
if (row != null) {
  sum += row["LineTotal"];
}

有关详细信息,请参阅:http://msdn.microsoft.com/en-us/library/bb299031.aspx

然而,更强大的方法是在任何数据绑定之前计算这个。所以,这将是可重用的,并且视图不必计算所有这些:

public class InvoiceLine {
  public Decimal Line { get; set; }
}

public class Invoice {
  public IList<InvoiceLine> Lines { get; set; }
  public Decimal Total {
    get {
      return Lines.Sum(l => l.Line);
    }
  }
}

protected void Page_Load(...) {
  var invoice = SomeInvoiceService.GetInvoice(id);
  ProductListView.DataSource = invoice.Lines;
  ProductListView.DataBind();

  TotalLabel.Text = String.Format("{0:C}", invoice.Total);
}

ASPX文件:

<asp:ListView ID="ProductListView" runat="server">
  <ItemTemplate>
    <%# String.Format("{0:C}", Eval("Line")); %>
  </ItemTemplate>
</asp:ListView>