[英]DataGridView custom sort not on DataMember (Databound Grid)
我有一个自定义DataGridView列,该列使用嵌入式控件,该控件会弹出一个搜索窗口以查询该列的值。 重要的是数据绑定列是数字ID,但自定义列单元格显示文本描述。
如何获得按文本说明而不是数字ID排序的列?
我看不到一种方法来覆盖列以按FormattedValue而不是Value进行排序。 我可以确保说明在数据表中显示为单独的列,但是我看不到有任何说法“将VALUE_ID列用作DataMember,但将VALUE_DESCRIPITON列用作'SortMember'”
您可以使用以下文章“ 列排序模式”中描述的技术
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();
}
您使用什么作为数据源? DataTable
? 排序最通常由列表本身提供,因此您实际上可以使用自己的特定排序行为编写自定义列表。 最简单的方法(尽管仍然很简单)是从BindingList<T>
继承,并重写ApplySortCore
, RemoveSortCore
, SupportsSortingCore
, IsSortedCore
, SortPropertyCore
和SortDirectionCore
( IsSortedCore
!)。 特别是, ApplySortCore
将必须检测特定的PropertyDescriptor
,并执行定制搜索。
我并不是说这很简单(相反),但是可以在标准绑定机制中完成。
另一种想法可能是将id设置为其他名称,实际上不是int而是自定义类/结构。 它需要实现IComparable
/ IComparable<T>
,并具有显示所需文本的ToString()
。 然后,您大概可以(未经测试)直接绑定到该列。
然而!!! 如果您还不熟悉System.ComponentModel
,那么建议您避免这种复杂性。 如果上述说法合理,那就很好-如果不是,我不确定我是否会在您第一次刺入该区域时尝试...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.