【问题标题】:Custom sorting with binding source in compact framework?在紧凑框架中使用绑定源进行自定义排序?
【发布时间】:2013-01-07 23:26:34
【问题描述】:

这就是我目前的排序方式:

 BindingSource bs = ( BindingSource )m_dataGrid.DataSource;
bs.Sort = "SortingRow" + " DESC";

我想要的是自定义方法或我可以用来排序的东西,例如:

bool GreaterThan(object a, object b)
{
(...)//my own code to determine return value
}

我怎样才能做到这一点?

【问题讨论】:

标签: c# datagrid windows-mobile compact-framework


【解决方案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() 工作,您需要在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

}

希望对你有帮助。

不过,我真的不能花更多时间在这上面,因为我今天有最后期限。

~乔

【讨论】:

  • 谢谢,这正是我想要的! :)
猜你喜欢
  • 2012-03-06
  • 2013-08-23
  • 2014-11-19
  • 1970-01-01
  • 2011-03-15
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多