![](/img/trans.png)
[英]How to do multiple cells in a single row column using GridView Control
[英]Sum of GridView Column using Row Cells
我試圖找到我的網格視圖中列的所有單元格的總和。 但是我得到了錯誤:
我試圖計算整個列並將其放在gridview之外的標簽中。
Row.Cells [4]的輸出為459.00
輸入的字符串格式不正確。
在線:第509行:sum + = Decimal.Parse(c.Text);
這是我的代碼:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
// Set the capacity label text
Label4.Text = e.Row.Cells[4].Text;
// Calc the sum of all of the row values
decimal sum = 0;
foreach (TableCell c in e.Row.Cells)
{
sum += Decimal.Parse(c.Text);
}
// Set the sum label text value
Label5.Text = sum.ToString();
}
}
使總和成為全局變量。
decimal sum = 0;
然后為每一行添加到全局變量:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null)
{
// Set the capacity label text
sum += Decimal.Parse(e.Row.Cells[4].Text);
}
}
然后在page_prerender中放入以下內容:
// Set the sum label text value
Label5.Text = sum.ToString();
您可能還需要檢查Row.ItemType是項目,而不是標題。 另外,這樣做更安全:
decimal val;
foreach (..)
{
//only call Trim() if you know the text is not null.
If (Not Decimal.TryParse(c.Text.Trim()), out val) {
//error condition; you can throw an exception just for testing to verify something is or isn't right
throw new Exception("Error, field is not a decimal: " + c.Text);
}
else {
sum += val;
}
同樣,任何總計也必須在ItemDataBound事件之外進行。 因此,將總計設置為標簽不是正確的時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.