Tuesday, June 22, 2010

How to use Grouping in DataGrid Silverlight 3 Control

In this post I will show you how you can use the grouping feature provided by the data grid control of silver light 3 control. I will show you how you can group the data grid data at run time. Below is the image of the screen which I have develop for this example. Here you can see that I have three control one is label , second one is the combo Box for the selection of the group name and third one is the data grid to show the grouped data. When application start you can see that combo box has no selected value by default so no grouping is applied and all the data are shown as it was placed in the collection.

Here is my code which is used to group the collection based on the selection value in the combo box control, the combo box control contain only two item one for the gender and second one for the age. As I want to group the collection on these two value mean gender and age. The code is written in the Selection changed event handler of the combBox and here you can see that I have usese the PageCollectionView class which is in the System.Windows.Data namespace. I have declared collection objec of PageCollectionView class and used the GroupDescription Property to add the property name.
if (cboGroupName.SelectedIndex == 0)
{
collection = new PagedCollectionView(myPersonList);
collection.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
grdDataGrid.ItemsSource = collection; ;
}
else
{
collection = new PagedCollectionView(myPersonList);
collection.GroupDescriptions.Add(new PropertyGroupDescription("Age"));
grdDataGrid.ItemsSource = collection; ;
}

When you select value from the combo Box it will group them on that value mean if you select gender then grouping is applied on gender and else it will be applied on age.You can download the source code from here
All and any comments / bugs / suggestions are welcomed!

No comments: