【问题标题】:Calculating Total in Gridview when autogenerate columns is set to false当自动生成列设置为 false 时在 Gridview 中计算总计
【发布时间】:2017-04-18 16:05:01
【问题描述】:

我有一个将 autogeneratecolumns 设置为 false 的 gridview。这些列可以根据数据动态生成,因此此网格视图显示了一个人在每个应用程序上花费了多少小时 - Test1、test2、Test3 和 Test4 是人的姓名,项目(应用程序)列在左侧。下面是网格视图

   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

我需要为所有列动态计算网格视图页脚中的总数。当我不知道可以有多少列并且这些列来自查询时,我该如何实现这一点。我只是从我的查询中显示网格视图,这就是我将 autogeneratecolumns 设置为 false 的原因。

我们将不胜感激。

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    您可以在 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);
        }
    }
    

    【讨论】:

    • 我不知道该列的名称。它的动态
    • 更新了我的答案。只需使用索引row[0]
    • 我的列号也是动态的。只有第一列是字符串,根据是否有新人加入团队,可以添加其他列,因此可能会有人员 test5。我将如何处理
    • 计算列数并执行for 循环。
    猜你喜欢
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多