2

ショッピングカートを表示するListViewがあります。String.Formatを追加して、LineTotalの10進数を通貨文字列として表示するまでは、正常に機能していました。LineTotalでEvalを実行したときに機能していました。

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;

            }
        }
4

1 に答える 1

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>
于 2012-06-28T15:03:02.780 に答える