【问题标题】:How can I tally up the total count of my columns?如何计算我的列总数?
【发布时间】:2011-08-31 19:32:53
【问题描述】:

我正在使用数据网格自动生成我的列。如何获取已创建和已兑换的列的总数?

DbCommand dbCommand = db.GetStoredProcCommand("sel_TotalCount_p");
db.AddInParameter(dbCommand, "@pDateFrom", DbType.Date, datePicker1.Text);
db.AddInParameter(dbCommand, "@pDateTo", DbType.Date, datepicker2.Text);
ds = db.ExecuteDataSet(dbCommand);

ds.Tables[0].Rows.Add("Total");

DataGrid2.DataSource = ds;
DataGrid2.DataBind();

【问题讨论】:

  • 什么是createdredeemed 列?我不明白你的意思。
  • 这些是从 SQL 返回的列。
  • 如果您从存储过程中获取值,为什么不让它也返回总数?
  • im 在 sql server 2000 上,按我需要的方式旋转表格太复杂了。我认为之后使用 C# 计算列的值会更容易。

标签: c# .net datagrid


【解决方案1】:

可以编写一个“RowDataBound()”事件并单独总结。如下所示。

    public int totalCount = default(int);

    protected void Test_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType.Equals(DataControlRowType.DataRow))
        {
            int count = default(int);
            string text = e.Row.Cells[0].Text;
            int.TryParse(text, out count);
            totalCount = totalCount + count;
        }
    }

希望对你有用!!

【讨论】:

  • 我必须在某个地方调用它吗?如何在我的代码中实现它?我将它添加为我的总计数代码下方的新方法。
  • 如果是 GridView 则需要添加事件“RowDataBound”,如果是数据网格则需要在“.aspx 页面”中添加“OnDataBound”( 标签包含此事件)并添加将此代码添加到相应的“.cs”文件中,该文件将为您提供计数。
【解决方案2】:

如果您指的是列的总和,而不是计数,并且假设返回的 DataSet 的架构是您所显示的,那么请尝试:

DataTable dt = ds.Tables[0];
int totalCreated = 0;
int totalRedeemed = 0;
foreach (DataRow dr in dt.Rows)
{
    totalCreated += Convert.ToInt32(dr["Created"]);
    totalRedeemed += Convert.ToInt32(dr["Redeemed"]);
}

DataRow r = dt.NewRow();
r["CreationDate"] = "Total";
r["Created"] = totalCreated;
r["Redeemed"] = totalRedeemed;
dt.Rows.Add(r);

请注意,这会将行添加到 DataSource,并且就您的 DataGrid 而言,它只是另一行数据。不要尝试对 DataGrid 进行排序或编辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    相关资源
    最近更新 更多