Custom DataGridView not for DataMember (data binding grid)
I have a custom DataGridView column that uses an inline control that displays a search box for the value of that column. The important thing is that the data column is a numeric identifier, but custom column cells display a textual description.
How do I get a column to sort by text description and not by numeric ID?
I don't see a way to override the column to sort by FormattedValue instead of Value. I could verify that the description appears as a separate column in my data table, but I don't see any way to say "use the VALUE_ID column as DataMember, but the VALUE_DESCRIPITON column as" SortMember ""
source to share
You can use the technique described in the following article Ways to Sort Columns
private bool ascending;
private int sortColumn;
private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
List<SomeObject> list = (List<SomeObject>)someBindingSource.DataSource;
if (e.ColumnIndex != sortColumn) ascending = false;
int 1 = e.ColumnIndex;
if (i == DescriptionColumn.Index)
list.Sort(new Comparison<SomeObject>((x,y) => x.ID.CompareTo(y.ID)));
sortColumn = e.ColumnIndex;
ascending = !ascending;
if (!ascending) list.Reverse():
someBindingSource.ResetBindings(false);
// you may also have to call dgv.Invalidate();
}
source to share
What are you using as a data source? a DataTable
? The sort is most often provided by the list itself, so you can write your own list with your own specific sort. The simplest approach (although it is still a non-trivial) would have to inherit from BindingList<T>
and override ApplySortCore
, RemoveSortCore
, SupportsSortingCore
, IsSortedCore
, SortPropertyCore
and SortDirectionCore
(phew!). In particular, ApplySortCore
I would have to identify a specific PropertyDescriptor
and custom search.
I am not saying that this is trivial (quite the opposite), but it can be done within standard binding mechanisms.
An alternative idea might be to make id something else, i.e. not actually an int, but a regular class / structure. It would have to implement IComparable
/ IComparable<T>
and have ToString()
that renders the desired text. Then you can presumably (untested) directly bind to that column.
However!!! If you are not already familiar with System.ComponentModel
, I would suggest avoiding this complexity. If that makes sense, then great - if not, I'm not sure if I will try to do this for your first punch in this area ...
source to share