DataGridView Custom Sort in WinForm

Currently, the My DataGridView control is sorted using the Sort property of the associated data, but it does not do what I want.

I have a column with a name Employeethat displays as "Last Name First Name."

When I sort by Employee, the user name Amy Z_Lastname is preceded by the name John A_Lastname, which means that I prefer to sort the last names.

I can break the Employee line into 3 parts, include the ones in the DataTable, and set the sorting to "Lastname, Firstname", and then hide the Lastname and Firstname columns.

I'd rather learn to override IComparer by default (or something else) to provide instructions on how to sort as I want (the answer I would prefer).

+3
source share
1 answer

Custom Sorting in a DataGridView

DataGridView knows nothing about this rating, of course. By default, the sorting script (automatic sorting for a data-bound column) of calling DataGridView.Sort () through a column with a mouse click simply delegates the implementation of IBindingList ApplySort () in the list that you linked to the grid. Usually this list will be a DataView. Using my ObjectListView implementation, this will look at a list of arbitrary business objects. In any case, you will end up comparing the properties of the items in the list using the Incorrect implementation of the property type.

More details

PropertyComparers PropertyComparersCollection, IComparer. IComparer , ComparersCollection.Add() (, view.PropertyComparers [ "PropName" ] = myComparer). , PropertyComparersCollection.Remove() IComparer null .

IComparer PropertyComparers, IComparer. ObjectListView , IComparer PropertyComparers, .

, ObjectListView BeginUpdate() EndUpdate() ListChanged Sort , IComparers . DataGridView. ObjectListView , IComparers , .

, , IComparer , default IComparable .

:

private void radioButtonSortProgram_CheckedChanged(object sender, EventArgs e)

{

    if (this.radioButtonSortProgramAlpha.Checked)

        this.view.PropertyComparers["Program"] = new CustomerProgramComparerAlpha();

    else if (this.radioButtonSortProgramRank.Checked)

        this.view.PropertyComparers["Program"] = new CustomerProgramComparerRank();

    else

        this.view.PropertyComparers.Remove("Program");

}
+3

Source: https://habr.com/ru/post/1760391/


All Articles