【问题标题】:Sum of columns of a dynamically generated gridview动态生成的gridview的列总和
【发布时间】:2014-06-02 12:14:02
【问题描述】:

我需要在页脚中获取 gridview 的单元格的总和。
GridView 是动态生成的,然后显示在网页上。
如果cellId 指定,我可以得到任何列的总和,但是当我尝试申请循环时,它不起作用..

这是我到目前为止所做的......

if (e.Row.RowType == DataControlRowType.Header)  
{  
}  
else  
{  
    for (int i = 18; i < e.Row.Cells.Count; i++)  
    {  
     //  e.Row.Cells[i].Text = e.Row.Cells[i].Text.Trim().Replace("&nbsp;", "0").Replace("amp;", "0");  
         total[i] += Convert.ToDouble(e.Row.Cells[i].Text);  
    }  
}    

18 是从哪里开始计算总和的列数。 已放置注释行,因此没有空值或空白......

【问题讨论】:

  • 它不工作?你有一个例外或代码没有给你你应该拥有的东西?你不能做一个foreach循环吗? Foreach( Cell in e.Row.Cells) 或类似的东西?
  • foreach 单元格会遍历行的每个单元格,还有带有字符串和其他数据类型的列..
  • 并且没有错误或异常。

标签: c# asp.net .net gridview aspxgridview


【解决方案1】:

我不确定您遇到了什么实际问题,但是,您为什么不使用 DataControlRowType.Footer 和这个小 LINQ 查询:

if (e.Row.RowType == DataControlRowType.Footer)
{
    double cellValue = 0;
    double sum = e.Row.Cells.Cast<TableCell>().Skip(18)
        .Where(cell => double.TryParse(cell.Text, out cellValue))
        .Sum(cell => cellValue);
}

【讨论】:

  • 谢谢,但如果你能在代码中显示问题以及代码背后的逻辑,我将不胜感激,因为我没有使用过 LINQ...对不起,如果我冒犯了,但我正在努力学习...
  • @humorousdragon:这到底行得通吗?你不明白什么,LINQ 查询或者为什么这应该代替你的方法?由于if(header){}else{//now the datarows are following},您没有使用页脚而是使用数据行。
  • 我只是复制并使用它..但它没有工作..虽然它没有抛出任何异常..但到目前为止没有结果..而且我无法对数据列求和使用任何方法在页脚中显示...
【解决方案2】:

经过一番努力,我想通了...感谢您向我展示了正确的方向...

    if (GridView1.Rows.Count > 0)
    {
        int TtlRows = GridView1.Rows.Count;
        int TtlCol = GridView1.Rows[0].Cells.Count;
        int FxdCol = 1;
        int ComputedCol = TtlCol - FxdCol;

        for (int i = FxdCol; i < TtlCol; i++)
        {
            double sum = 0.000;

            for (int j = 0; j < TtlRows; j++)
            {
                sum += GridView1.Rows[j].Cells[i].Text != "&nbsp;" ? double.Parse(GridView1.Rows[j].Cells[i].Text) : 0.000;
            }
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[i].Text = sum.ToString("#0.000");
            }

        }  
    }

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 2017-02-02
    • 2011-12-09
    • 2019-02-06
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多