有很多方法可以做到。
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() 工作,您需要在MyStuff 类中实现IComparable 和IEquatable 接口。
给你一个想法的蹩脚的通用示例:
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
}
希望对你有帮助。
不过,我真的不能花更多时间在这上面,因为我今天有最后期限。
~乔