【问题标题】:.Net String.Format Currency in ItemTemplate with Subtotal in DataboundItemTemplate 中的 .Net String.Format 货币与数据绑定中的小计
【发布时间】:2012-06-28 14:38:46
【问题描述】:

我有一个显示购物车的 ListView。在我添加 String.Format 以将 LineTotal 小数显示为货币字符串之前,它工作正常。当我刚刚在 LineTotal 上进行 Eval 时,它正在工作。

当我添加 String.Format 时,问题就出现了——它弄乱了代码隐藏。错误:输入字符串的格式不正确。

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

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

ItemTemplate 的缩写:

<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;

            }
        }

【问题讨论】:

    标签: .net listview currency itemtemplate string.format


    【解决方案1】:

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

    首先,您得到的错误是因为 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>
    

    【讨论】:

    • 我应该在哪里直接设置DataItem?在同一个预渲染函数中?如果是这样,我得到一个错误,“运算符 += 不能应用于操作数'十进制'和'对象'。我在 Page_PreRender 中绑定列表视图而不加载。我稍后会尝试你的第二种方法,看起来不错,但我必须在数据层中更改一些内容。
    • 其实应该已经在你做ProductListView.DataSource = ...的地方设置好了!这是你的行应该被设置的地方。此外,您应该使用 Decimal.Parse() 将其转换为 Decimal,以便添加它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多