2

グリッドビューで特定の列の合計を設定する必要があります。

私のコードは次のとおりです。

<asp:TemplateField>
     <HeaderTemplate>
         Amount
     </HeaderTemplate>
     <ItemTemplate>
         <asp:Label ID="lblAmt" HeaderText="Amount" runat="server" 
              Text='<%# Eval("Amount")%>' Visible="true">
         </asp:Label>
     </ItemTemplate>
     <FooterTemplate>
         <asp:Label ID="lblTotalAmt" runat="server" />
     </FooterTemplate>
</asp:TemplateField>    

その後:

decimal totProfit = 0M;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
          Label lblAmt = (Label)e.Row.FindControl("lblAmt");
          decimal Profitprice = Decimal.Parse(lblAmt.Text);
          totProfit += Profitprice;
     }
     if (e.Row.RowType == DataControlRowType.Footer)
     {
          Label lblTotalAmt = (Label)e.Row.FindControl("lblTotalAmt");
          lblTotalAmt.Text = totProfit.ToString();
     }
 }     

しかし、エラーは次のようになりました:

入力文字列は、正しい形式ではありませんでした。

4

2 に答える 2

2

これはlblAmt、10 進数として無効な値が含まれている可能性があります。したがって、値が10進数に解析される必要があることを確認してください。Decimal.TryParseしたがって、このようなより安全なサイド使用のために

if (e.Row.RowType == DataControlRowType.DataRow)
{
  Label lblAmt = (Label)e.Row.FindControl("lblAmt");
  decimal Profitprice = 0;
  if(Decimal.TryParse(lblAmt.Text, out Profitprice));
  {
     totProfit += Profitprice;
  }
}
于 2013-05-15T13:16:27.077 に答える
2

ここで発生する可能性のある整数変換中に MS によって認識されるエラーがあります ( http://support.microsoft.com/kb/942460 )

もう 1 つのオプションは、[金額] フィールドに数値が入力されていることを確認することです。

decimal totProfit = 0M;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblAmt = (Label)e.Row.FindControl("lblAmt");
        decimal Profitprice; 
        if (Decimal.TryParse(lblAmt.Text, Profitprice) ) {
             totProfit += Profitprice;
        }
    }
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        Label lblTotalAmt = (Label)e.Row.FindControl("lblTotalAmt");
        lblTotalAmt.Text = totProfit.ToString();
    }
}     
于 2013-05-15T13:14:17.967 に答える