2011-10-27 39 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<>)); 
     }