繁体   English   中英

动态生成的gridview的列总和

[英]Sum of columns of a dynamically generated gridview

我需要在页脚中获取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是从此处开始计算总和的列数。 注释行已经放置,因此没有null或空白。...

我不确定您遇到了什么实际问题,但是,为什么不使用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);
}

经过一番工作后,我发现...感谢您向我展示了正确的方向...

    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");
            }

        }  
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM