[英]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.