Sort а DataTable Column That Contains Square Brackets in its Name in a RadGridView Scenario
Environment
Product Version | 2022.3.912 |
Product | RadGridView for WPF |
Description
The default sorting logic of RadGridView cannot sort a column that is bound to a DataTable column, which has square brackets in its name.
Solution
To achieve a sorting functionality in this scenario, implement custom sorting logic using the Sorting event of the RadGridView
control.
-
Subscribe to the Sorting event:
<telerik:RadGridView Sorting="OnRadGridViewSorting"/>
-
Retrieve the
DataView
of the DataTable instance that is bound to theItemsSource
property of RadGridView. Then, check if thee.Column
property contains the column that is bound to the DataTable column with square brackets in its name:Handling the Sorting event
private void OnRadGridViewSorting(object sender, Telerik.Windows.Controls.GridViewSortingEventArgs e) { var items = e.DataControl.ItemsSource as DataView; if (e.Column.UniqueName.Contains("MyColumnWithSquareBrackets")) { } }
-
Utilize the
Sort
property of the retrievedDataView
to sort the DataTable column in the direction of the new sorting state. The square brackets of the column will have to be escaped when using the Sort property:Setting the Sort property of the DataView
private void OnRadGridViewSorting(object sender, Telerik.Windows.Controls.GridViewSortingEventArgs e) { var items = e.DataControl.ItemsSource as DataView; if (e.Column.UniqueName.Contains("MyColumnWithSquareBrackets")) { if (e.NewSortingState == Telerik.Windows.Controls.SortingState.Ascending) { items.Sort = @"[[MyColumnWithSquareBrackets]]"; } else if (e.NewSortingState == Telerik.Windows.Controls.SortingState.Descending) { items.Sort = "[[MyColumnWithSquareBrackets]] desc"; } else { items.Sort = "[[MyColumnWithSquareBrackets]]"; } } }
-
Set the
SortingState
property of the sorted column to the new sorting direction. Then, to prevent the default sorting logic of RadGridView from occurring, set thee.Cancel
property to true:The complete implementation of the custom sorting logic
private void OnRadGridViewSorting(object sender, Telerik.Windows.Controls.GridViewSortingEventArgs e) { var items = e.DataControl.ItemsSource as DataView; if (e.Column.UniqueName.Contains("MyColumnWithSquareBrackets")) { if (e.NewSortingState == Telerik.Windows.Controls.SortingState.Ascending) { items.Sort = @"[[MyColumnWithSquareBrackets]]"; } else if (e.NewSortingState == Telerik.Windows.Controls.SortingState.Descending) { items.Sort = "[[MyColumnWithSquareBrackets]] desc"; } else { items.Sort = "[[MyColumnWithSquareBrackets]]"; } } e.Column.SortingState = e.NewSortingState; e.Cancel = true; }
The IsCustomSortingEnabled property of the column needes to be set to true, when implementing custom sorting logic.