2011-10-27 219 views
0

當我填寫的datagridview使用對象 的名單,我不能C#填充的DataGridView

但是列進行排序,我充滿了數據表 相同的DataGridView我可以排序列

如何當我工作,我可以對它進行排序與他們兩個?

回答

0

你可以將其轉換爲一個DataTable。可能不像實施BindingList<T>那樣乾淨和高效,但它有效。採取從...主知道在哪裏;不是原創的。重構了一下。

要使用:

List<MyObject> myObjects = GetFromDatabase(); // fake method of your choosing 
DataTable dataTable = ToDataTable(myObjects); 
yourDataGridView.DataSource = dataTable; 

ToDataTable等方法:

 public static DataTable ToDataTable<T>(IEnumerable<T> items) 
     { 
      var tb = new DataTable(typeof (T).Name); 
      PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 

      foreach (PropertyInfo prop in props) 
      { 
       Type t = GetCoreType(prop.PropertyType); 
       tb.Columns.Add(prop.Name, t); 
      } 

      foreach (T item in items) 
      { 
       var values = new object[props.Length]; 
       for (int i = 0; i < props.Length; i++) 
       { 
        values[i] = props[i].GetValue(item, null); 
       } 

       tb.Rows.Add(values); 
      } 
      return tb; 
     } 

     public static Type GetCoreType(Type t) 
     { 
      if (t != null && IsNullable(t)) 
      { 
       if (!t.IsValueType) 
       { 
        return t; 
       } 
       else 
       { 
        return Nullable.GetUnderlyingType(t); 
       } 
      } 
      else 
      { 
       return t; 
      } 
     } 

     public static bool IsNullable(Type t) 
     { 
      return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); 
     }