Reputation: 43
I'm auto-generating my columns using a datagrid. How can I get a total of the created and redeemed columns?
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();
Upvotes: 2
Views: 272
Reputation: 21722
If you mean the sum of the columns, not the count, and assuming the schema of the returned DataSet is what you have shown, then try:
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);
Be aware this adds the row to the DataSource and, so far as your DataGrid is concerned, it's just another row of data. Do not try to sort or edit the DataGrid.
Upvotes: 0
Reputation: 1449
Can write a "RowDataBound()" event and sum that up seperately. Something like below.
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;
}
}
Hope this is useful!!
Upvotes: 3