首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当自动生成列设置为false时,在Gridview中计算总计

当自动生成列设置为false时,在Gridview中计算总计
EN

Stack Overflow用户
提问于 2017-04-18 16:05:01
回答 1查看 835关注 0票数 0

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

代码语言:javascript
复制
   Projects       Test1        Test2       Test3

    Tickets           8           10    0

    maintenance       9       11         13


     Writing web       8            9          8

    Total             25          30           21    

当我在数据库中添加一个新项目时,上面的网格视图可以动态地更改,并且一个新的人为新项目输入他的时间,所以上面的网格视图可以变成这样

代码语言:javascript
复制
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的原因。

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-18 16:22:20

您可以在OnRowDataBound事件的GridView中这样做。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43477100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档