2017-04-18 23 views
0

我有一個gridview,它將autogeneratecolumns設置爲false。這些列可以根據數據動態生成,因此這個gridview顯示了一個人在每個應用程序上花費了多少小時 - Test1,test2,Test3和Test4是人名,項目(應用程序)列在左邊。下面是在GridView當自動生成列設置爲false時,計算Gridview中的總數

Projects  Test1  Test2  Test3 

    Tickets   8   10 0 

    maintenance  9  11   13 


    Writing web  8   9   8 

    Total    25   30   21  

,當我在數據庫中添加一個新的項目和新的人進入他的新項目小時,上述網格視圖可以變成這個樣子

上述網格視圖可以動態改變
Projects  Test1  Test2  Test3  Test4 

Tickets   8   10 0   0 

maintenance  9  11   13  0 


Writing web  8   9   8  0 

VSS             12.5 

Total    25   30   21  12.5 

我需要爲所有列動態計算gridview頁腳中的總數。當我不知道有多少列可以存在且列來自查詢時,我該如何實現這一目標。我只是從我的查詢中顯示網格視圖,這就是爲什麼我將autogeneratecolumns設置爲false的原因。

任何幫助將不勝感激。

回答

0

您可以在GridView的OnRowDataBound事件中執行此操作。

decimal total; 

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    //check if the current row is a datarow or the footer row 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     //cast the row back to a datarowview 
     DataRowView row = e.Row.DataItem as DataRowView; 

     //add the column value to the totals 
     total += Convert.ToDecimal(row["Test1"]); 

     //or by column index 
     total += Convert.ToDecimal(row[0]); 
    } 
    else if (e.Row.RowType == DataControlRowType.Footer) 
    { 
     //find a label in the footer with findcontrol 
     Label label = e.Row.FindControl("Label1") as Label; 

     //set the total value in the label 
     label.Text = string.Format("{0:N2}", total); 

     //set the footer value by cell index instead of a label 
     e.Row.Cells[1].Text = string.Format("{0:N2}", total); 
    } 
} 
+0

我不知道列的名稱。它的動態 – Anjali

+0

更新了我的答案。只需使用索引'row [0]' – VDWWD

+0

我的列號也是動態的。只有第一列是字符串,其他人可以添加,這取決於新加入的人是否剛剛加入團隊,因此可能會有人test5。我將如何處理 – Anjali

相關問題