如何在C#中的gridview中设置页脚中特定列的总和?

时间:2013-05-15 13:08:54

标签: c# asp.net

我需要在gridview中设置特定列的总和。

我的代码是:

<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();
     }
 }     

但错误就像:

  

输入字符串的格式不正确。

2 个答案:

答案 0 :(得分:2)

在整数转换过程中,MS可能会在此处发现错误(http://support.microsoft.com/kb/942460

另一种选择是确保它是'Amount'字段中的数字。

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();
    }
}     

答案 1 :(得分:2)

这可能是因为您的lblAmt可能包含对小数无效的值。因此,请确保您的值应解析为十进制。因此,对于更安全的一面使用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;
  }
}