This is a migrated thread and some comments may be shown as answers.

How to group by month?

2 Answers 194 Views
Grid
This is a migrated thread and some comments may be shown as answers.
tomekm
Top achievements
Rank 1
tomekm asked on 17 Aug 2010, 09:28 AM
I want my grid to group by column which contains Date but group not by day but months so items (invoices) are grouped monthly.

2 Answers, 1 is accepted

Sort by
0
Schlurk
Top achievements
Rank 2
answered on 18 Aug 2010, 08:00 PM
So there's no direct easy way to say "Group this by Month" however, there is a pretty neat little trick that you can use to get the same functionality. Basically what you do is create a new column, lets say "MonthColumn", and set its Visible or Display property to false. Then in the DataSet or DataTable that you have bound to the table you can do the following:

private DataTable CreateMonthColumn(DataTable TestTable)
{
    DataTable TableToReturn = new DataTable();
    DataTable PassedTable = TestTable;
 
    DataColumn MyColumn = new DataColumn("MonthColumn");
    MyColumn.DataType = System.Type.GetType("System.DateTime");
    PassedTable.Columns.Add(MyColumn);
 
    foreach (DataRow CurrentRow in PassedTable.Rows)
    {
        DateTime MyTime = new DateTime();
        MyTime = (DateTime)CurrentRow["Date"];
        DateTime MonthTime = new DateTime(MyTime.Year, MyTime.Month, 1);
        CurrentRow["MonthColumn"] = MonthTime;
    }
 
    TableToReturn = PassedTable;
 
    return TableToReturn;
}

So essentially what you do is create a new column in the underlying datasource, set all the DateTime to be yyyy/mm/1 (making them all the first of that month) and then you can simply group by that column (that is not visible) either declaratively or programmatically. This allows you to group your data by month without too much hassle!
0
tomekm
Top achievements
Rank 1
answered on 19 Aug 2010, 09:41 PM
Thanks, that's a good idea.
Tags
Grid
Asked by
tomekm
Top achievements
Rank 1
Answers by
Schlurk
Top achievements
Rank 2
tomekm
Top achievements
Rank 1
Share this question
or