簡體   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