2012-06-28 32 views
2

我有一個顯示購物車的ListView。直到我添加String.Format以將LineTotal小數顯示爲貨幣字符串時,它工作正常。當我剛剛在LineTotal上進行Eval時,它正在工作。.Net String.Format ItemTemplate中的貨幣與數據綁定中的小計

當我添加String.Format時會發生問題 - 它會擾亂代碼隱藏。錯誤:輸入字符串格式不正確。

在C#中,我採用文本標籤的值,並在整個代碼隱藏中使用它來完成諸如產品總值(sum var)之類的操作。

我想PriceLabel價格顯示爲貨幣,但也可以使用我的Listview數據綁定函數中的標籤值,以便我可以更新總和變種。

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

      } 
     } 

回答

2

我覺得你的做法是不是在這種情況下,確實不錯。

首先,你得到的錯誤是因爲lbl.Text可能是空的,因爲綁定正在進行(請參閱ASPX文件中的值將設置AFTER 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> 
+0

會在哪裏我直接設置DataItem的?在相同的預渲染功能?如果是這樣,我得到一個錯誤,「運算符+ =不能應用於操作數的'小數'和'對象'我綁定了Page_PreRender中的列表視圖並且沒有加載,我會稍後嘗試你的第二種方法,但我不得不在數據層中更改一些東西 – User970008

+0

事實上,它應該已經設置在哪裏了ProductListView.DataSource = ...!這是你的行應該設置的位置,而且,你應該把它作爲十進制使用Decimal.Parse(),所以你可以添加它們。 – Allov