这就是我目前的做法:
BindingSource bs = ( BindingSource )m_dataGrid.DataSource;
bs.Sort = "SortingRow" + " DESC";
我想要的是一种自定义方法或我用来排序的东西,例如:
bool GreaterThan(object a, object b)
{
(...)//my own code to determine return value
}
我怎样才能完成这项工作?
答案 0 :(得分:1)
有很多方法可以做到。
DataSource对象通常可以转换回DataTable,DataView或其他任何东西。
不知道你的项目,我将使用DataTable。
添加数据后,将其强制转换回DataTable。
private void AddData(object data) {
// data would be what you would normally fill to the m_dataGrid.DataSource
DataTable table = m_dataGrid.DataSource as DataTable;
if (table == null) {
DataView view = m_dataGrid.DataSource as DataView;
if (view != null) {
table = view.Table;
}
}
if (table != null) {
Sort(table);
}
}
AddData
看起来的方式无关紧要,因为您只想要一种方法将已知数据传递给Sort
例程。
你的Sort
例程需要是你写的东西。它将原始数据更改回结构化数据类型,此处显示为通用MyStuff
类:
private void Sort(DataTable table) {
List<MyStuff> list = new List<MyStuff>(table.Rows.Count);
for (int i = 0; i < table.Rows.Count; i++) {
string valueA = table.Rows[MyStuff.A_INDEX].ToString();
int itemB = Convert.ToInt32(table.Rows[MyStuff.B_INDEX]);
list.Add(new MyStuff() { ValueA = valueA, ItemB = itemB });
}
list.Sort();
m_dataGrid.DataSource = list;
}
要使list.Sort()
生效,您需要在IComparable
课程中实施IEquatable
和MyStuff
接口。
蹩脚的通用示例给你一个想法:
class MyStuff : IComparable<MyStuff>, IEquatable<MyStuff> {
public const int A_INDEX = 0;
public const int B_INDEX = 0;
public MyStuff() {
ValueA = null;
ItemB = 0;
}
public string ValueA { get; set; }
public int ItemB { get; set; }
#region IComparable<MyStuff> Members
public int CompareTo(MyStuff other) {
if (other != null) {
if (!String.IsNullOrEmpty(ValueA) && !String.IsNullOrEmpty(other.ValueA)) {
int compare = ValueA.CompareTo(other.ValueA);
if (compare == 0) {
compare = ItemB.CompareTo(other.ItemB); // no null test for this
}
return compare;
} else if (!String.IsNullOrEmpty(other.ValueA)) {
return -1;
}
}
return 1;
}
#endregion
#region IEquatable<MyStuff> Members
public bool Equals(MyStuff other) {
int compare = CompareTo(other);
return (compare == 0);
}
#endregion
}
我希望有所帮助。
但是,我真的不能花更多的时间在这上面,因为我今天有一个截止日期。〜乔