如何排序数据绑定DataGridView列? [英] How to sort databound DataGridView column?
问题描述
如何通过点击列标题进行排序?
如何修改此代码来完成这项工作?
public partial class Form1:Form
{
public Form1()
{
列表< MyClass> list = new List< MyClass>();
list.Add(new MyClass(Peter,1202));
list.Add(new MyClass(James,292));
list.Add(new MyClass(Bond,23));
BindingSource bs = new BindingSource();
bs.DataSource = list;
DataGridView dg = new DataGridView();
DataGridViewTextBoxColumn c = new DataGridViewTextBoxColumn();
c.Name =name;
c.DataPropertyName =Name;
dg.Columns.Add(c);
c = new DataGridViewTextBoxColumn();
c.Name =number;
c.DataPropertyName =Number;
dg.Columns.Add(c);
dg.DataSource = bs;
this.Controls.Add((Control)dg);
}
}
class MyClass:IComparable&MyClass>
{
public string Name {get;组; }
public int Number {get;组;
public MyClass(){}
public MyClass(string name,int number)
{
Name = name;
Number = number;
}
public override string ToString()
{
return string.Format({0}:{1},Name,Number);
}
#region IComparable< MyClass>成员
public int CompareTo(MyClass other)
{
return Name.CompareTo(other.Name);
}
#endregion
}
我记得有一些问题找到可以工作的东西,当我添加排序到我的datagrids也。您可以通过首先向项目添加以下类来实现可排序的可绑定列表。它是实现 BindingList< T>
的列表实现,以便您可以将数据网格绑定到它,并且还支持排序。有关详细信息的更好的解释是 MSDN这里
public class SortableBindingList< T> :BindingList< T>
{
private ArrayList sortedList;
private ArrayList unsortedItems;
private bool isSortedValue;
public SortableBindingList()
{
}
public SortableBindingList(IList< T>列表)
{
foreach对象o在列表中)
{
this.Add((T)o);
}
}
保护覆盖bool SupportsSearchingCore
{
get
{
return true;
}
}
protected override int FindCore(PropertyDescriptor prop,object key)
{
PropertyInfo propInfo = typeof(T).GetProperty(prop。名称);
T项;
if(key!= null)
{
for(int i = 0; i< Count; ++ i)
{
item =(T)项[i];
if(propInfo.GetValue(item,null).Equals(key))
return i;
}
}
return -1;
public int Find(string属性,对象键)
{
PropertyDescriptorCollection属性=
TypeDescriptor.GetProperties(typeof(T));
PropertyDescriptor prop = properties.Find(property,true);
if(prop == null)
return -1;
else
返回FindCore(prop,key);
}
protected override bool SupportsSortingCore
{
get {return true; }
}
protected override bool IsSortedCore
{
get {return isSortedValue; }
}
ListSortDirection sortDirectionValue;
PropertyDescriptor sortPropertyValue;
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction)
{
sortedList = new ArrayList();
类型interfaceType = prop.PropertyType.GetInterface(IComparable);
if(interfaceType == null&& prop.PropertyType.IsValueType)
{
Type底层类型= Nullable.GetUnderlyingType(prop.PropertyType);
if(underlyingType!= null)
{
interfaceType =底层类型.GetInterface(IComparable);
}
}
if(interfaceType!= null)
{
sortPropertyValue = prop;
sortDirectionValue = direction;
IEnumerable< T> query = base.Items;
if(direction == ListSortDirection.Ascending)
{
query = query.OrderBy(i => prop.GetValue(i));
}
else
{
query = query.OrderByDescending(i => prop.GetValue(i));
}
int newIndex = 0;
foreach(查询中的对象项)
{
this.Items [newIndex] =(T)项;
newIndex ++;
}
isSortedValue = true;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset,-1));
}
{
抛出新的NotSupportedException(不能排序+ prop.Name +
。这个+ prop.PropertyType。 ToString()+
不实现IComparable);
}
}
protected override void RemoveSortCore()
{
int position;
对象temp;
if(unsortedItems!= null)
{
for(int i = 0; i< unsortedItems.Count;)
{
position = this.Find(LastName,
unsortedItems [i] .GetType()。
GetProperty(LastName)。GetValue(unsortedItems [i],null));
if(position> 0&& position!= i)
{
temp = this [i];
this [i] = this [position];
这个[position] =(T)temp;
i ++;
}
else if(position == i)
i ++;
else
unsortedItems.RemoveAt(i);
}
isSortedValue = false;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset,-1));
}
}
public void RemoveSort()
{
RemoveSortCore();
}
protected override PropertyDescriptor SortPropertyCore
{
get {return sortPropertyValue;
}
protected override ListSortDirection SortDirectionCore
{
get {return sortDirectionValue; }
}
}
有了这个,只需要对上面发布的代码进行更改即可根据您的列表创建一个SortableBindingList,并绑定到可排序列表,而不是标准列表,如下所示:
列表< MyClass> list = new List< MyClass>();
list.Add(new MyClass(Peter,1202));
list.Add(new MyClass(James,292));
list.Add(new MyClass(Bond,23));
//添加可排序列表...
可排序绑定列表< MyClass> sortableList = new SortableBindingList&MyClass>(list);
BindingSource bs = new BindingSource();
bs.DataSource = sortableList; //绑定到可排序列表
这将足以让你走。
I know that there are a lot of questions on this topic. I have been through all of them but nothing seems to help.
How to sort by clicking on column header?
How should I modify this code to do the job?
public partial class Form1 : Form
{
public Form1()
{
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass("Peter", 1202));
list.Add(new MyClass("James", 292));
list.Add(new MyClass("Bond", 23));
BindingSource bs = new BindingSource();
bs.DataSource = list;
DataGridView dg = new DataGridView();
DataGridViewTextBoxColumn c = new DataGridViewTextBoxColumn();
c.Name = "name";
c.DataPropertyName = "Name";
dg.Columns.Add(c);
c = new DataGridViewTextBoxColumn();
c.Name = "number";
c.DataPropertyName = "Number";
dg.Columns.Add(c);
dg.DataSource = bs;
this.Controls.Add((Control)dg);
}
}
class MyClass:IComparable<MyClass>
{
public string Name { get; set; }
public int Number { get; set; }
public MyClass(){}
public MyClass(string name,int number)
{
Name = name;
Number = number;
}
public override string ToString()
{
return string.Format("{0}:{1}",Name,Number);
}
#region IComparable<MyClass> Members
public int CompareTo(MyClass other)
{
return Name.CompareTo(other.Name);
}
#endregion
}
I recall having issues finding something that would work when I added sorting to my datagrids too. You can implement a sortable bindable list by first adding the following class to your project. It is a list implementation that implements BindingList<T>
, so that you can bind your datagrid to it, and it also supports sorting. A better explanation of the details than I could give is on MSDN here
public class SortableBindingList<T> : BindingList<T>
{
private ArrayList sortedList;
private ArrayList unsortedItems;
private bool isSortedValue;
public SortableBindingList()
{
}
public SortableBindingList(IList<T> list)
{
foreach (object o in list)
{
this.Add((T)o);
}
}
protected override bool SupportsSearchingCore
{
get
{
return true;
}
}
protected override int FindCore(PropertyDescriptor prop, object key)
{
PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);
T item;
if (key != null)
{
for (int i = 0; i < Count; ++i)
{
item = (T)Items[i];
if (propInfo.GetValue(item, null).Equals(key))
return i;
}
}
return -1;
}
public int Find(string property, object key)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
PropertyDescriptor prop = properties.Find(property, true);
if (prop == null)
return -1;
else
return FindCore(prop, key);
}
protected override bool SupportsSortingCore
{
get { return true; }
}
protected override bool IsSortedCore
{
get { return isSortedValue; }
}
ListSortDirection sortDirectionValue;
PropertyDescriptor sortPropertyValue;
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction)
{
sortedList = new ArrayList();
Type interfaceType = prop.PropertyType.GetInterface("IComparable");
if (interfaceType == null && prop.PropertyType.IsValueType)
{
Type underlyingType = Nullable.GetUnderlyingType(prop.PropertyType);
if (underlyingType != null)
{
interfaceType = underlyingType.GetInterface("IComparable");
}
}
if (interfaceType != null)
{
sortPropertyValue = prop;
sortDirectionValue = direction;
IEnumerable<T> query = base.Items;
if (direction == ListSortDirection.Ascending)
{
query = query.OrderBy(i => prop.GetValue(i));
}
else
{
query = query.OrderByDescending(i => prop.GetValue(i));
}
int newIndex = 0;
foreach (object item in query)
{
this.Items[newIndex] = (T)item;
newIndex++;
}
isSortedValue = true;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
else
{
throw new NotSupportedException("Cannot sort by " + prop.Name +
". This" + prop.PropertyType.ToString() +
" does not implement IComparable");
}
}
protected override void RemoveSortCore()
{
int position;
object temp;
if (unsortedItems != null)
{
for (int i = 0; i < unsortedItems.Count; )
{
position = this.Find("LastName",
unsortedItems[i].GetType().
GetProperty("LastName").GetValue(unsortedItems[i], null));
if (position > 0 && position != i)
{
temp = this[i];
this[i] = this[position];
this[position] = (T)temp;
i++;
}
else if (position == i)
i++;
else
unsortedItems.RemoveAt(i);
}
isSortedValue = false;
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
}
public void RemoveSort()
{
RemoveSortCore();
}
protected override PropertyDescriptor SortPropertyCore
{
get { return sortPropertyValue; }
}
protected override ListSortDirection SortDirectionCore
{
get { return sortDirectionValue; }
}
}
With that in place, the only changes you need to make to the code that you have posted above is to create a SortableBindingList based on your list and bind to the sortable list, rather than the standard one, like so:
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass("Peter", 1202));
list.Add(new MyClass("James", 292));
list.Add(new MyClass("Bond", 23));
// Added sortable list...
SortableBindingList<MyClass> sortableList = new SortableBindingList<MyClass>(list);
BindingSource bs = new BindingSource();
bs.DataSource = sortableList; // Bind to the sortable list
And that will be enough to get you going.
这篇关于如何排序数据绑定DataGridView列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!