japhwil
japhwil

Reputation: 309

WPF DataGrid - Custom Sorting with DataTable as ItemsSource

Using a DataGrid, I display a DataTable with content generated at runtime. I therefore cannot use predefined columns. Each row contains a name as its first element and then a variable number of data that are usually numeric but may also be null or the string "Invalid".

Currently all data is interpreted as strings, which causes the problem that sorting a column results in an alphabetic order, not a numeric one, e.g. "0, 1, 12, 20, 3" instead of "0, 1, 3, 12, 20". I tried to work around this by either inheriting all displayed data from IComparable<T> (which the DataGrid ignores), or by overriding the OnSorting() method of DataGrid (for which I only found sources that assume I am using ListCollectionViews, not DataTables).

Does anyone know how to implement custom sorting behavior on a DataGrid that is bound to a DataTable generated at runtime?

Upvotes: -2

Views: 461

Answers (1)

RolandJS
RolandJS

Reputation: 1055

I would work with the DataTable instead of tampering with the DataGrid.

If can't do anything with the source to the DataTable, you can use a DataView to get a sorted view of the DataTable (see DataView.Sort).

Bind the DataView to the DataGrid.

Add an extra column and use DataColumn.Expression to convert the string values to numeric values and handle the null and Invalid values.

See the example here:

https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.expression?view=netframework-4.8

Upvotes: 1

Related Questions