Sebastian Sebastian - 1 year ago 171
C# Question

WPF Datagrid grouping with Datatable as ItemSource

I have a problem with grouping the data inside a datagrid.
The data is contained inside a Datatable which is filled from a SQL Database and binded to my datagrid. This is all working fine...

Now I want to group my datagrid by the field 'ID' which contains the same number multiple times... I already tried a lot of possible solutions which I found here and there, but none of them are working. Most of them uses CollectionViewSource instead of a Datatable...

Isn't there any direct way to group (+filter) my datatable and show it in a datagrid?
I hope anyone can help me to find an easy way or at least give me a hint what I need to look for.

To get the Data from the SQL Database I use the following (simplified) code:

this.db = new DBConnection(...);
DataTable dt_Applications =
this.db.ExecuteReader( Properties.SqlQueries.SQL_GetApplications );


<DataGrid Name="dg_Applications"
ItemsSource="{Binding dt_Applications}"
AutoGenerateColumns="True" />

The Data will look like:

[ID] [Name] [Var1] [Var2]
0 "App0" "Value0.1.0" "Value0.2.0"
0 "App0" "Value0.1.1" "Value0.2.1"
0 "App0" "Value0.1.2" "Value0.2.2"
1 "App1" "Value1.1.0" "Value1.2.0"
2 "App2" "Value2.1.0" "Value2.2.0"
2 "App2" "Value2.1.1" "Value2.2.1"


[ID] [Name] [Var1] [Var2]
"App0 [0]:"
- - "Value0.1.0" "Value0.2.0"
- - "Value0.1.1" "Value0.2.1"
- - "Value0.1.2" "Value0.2.2"
"App1 [1]:"
- - "Value1.1.0" "Value1.2.0"
"App2 [2]:"
- - "Value2.1.0" "Value2.2.0"
- - "Value2.1.1" "Value2.2.1"

Answer Source

I found a solution for my problem...

It is possible to bind the DataTable directly to a CollectionViewSource Object!

With this, there is nothing more to do. The DataGrid gets automatically reloaded when the DataTable was changed. All grouping and filtering can be done with it like described in the link from Alex Bell.

    <CollectionViewSource x:Key="cvsDataTable" Source="{Binding dt_myDataTable}">
            <PropertyGroupDescription PropertyName="ID"/>

<DataGrid Name="dg_myDataTable" ItemsSource="{Binding Source={StaticResource cvsDataTable}}">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download