2

我需要在 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();
     }
 }     

但是错误来了:

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

4

2 回答 2

2

在整数转换期间,MS 识别出一个错误,可能会在此处发挥作用 ( http://support.microsoft.com/kb/942460 )

另一种选择是确保它是“金额”字段中的数字。

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 回答
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;
  }
}
于 2013-05-15T13:16:27.077 回答