2013-05-15 25 views
2

我需要在gridview中設置一個特定列的總數。如何在C#中的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

有是可以被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(); 
    } 
}  
2

這可能是因爲你的lblAmt 5包含的值不是有效的小數。所以確保你的值應該被解析爲十進制。所以爲了更安全的一面使用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; 
    } 
} 
相關問題