我怎样才能统计我的列总数?

时间:2011-08-31 19:32:53

标签: c# .net datagrid

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

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();

example datagrid

2 个答案:

答案 0 :(得分:3)

可以写一个“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;
        }
    }

希望这很有用!!

答案 1 :(得分:0)

如果你的意思是列的总和,而不是计数,并假设返回的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。