2013-04-10 69 views
0

我有一个ListviewDataTable作为DataSource。现在我想用通用列表重新绑定它。之后,Listview数据,DataTable和通用列表数据都将被保留。可能吗?如何重新绑定列表视图已与数据表绑定

With DataTable装订Listview有3条记录。 现在我在Listview之外有一个添加按钮,我在添加按钮单击的通用列表中添加了一条新记录,然后我暂时想要显示这个新记录以及Listview1。最后,我在FinalSubmit的点击上添加了这个新记录。

回答

0

如果我正确地理解了这一点,您希望结合两种不同的数据类型,并将它们合并为一个,以便您可以将ListView与它绑定?

如果是这样,你将不得不将两者结合成一个SINGLE类型。你可以用下面的代码将你的通用列表转换成DataTable(扩展方法)。

/// <summary> 
/// Provides extensions to System.Linq object. 
/// </summary> 
public static class LinqExtensions 
{ 
    #region Methods 

    /// <summary> 
    /// Returns the underlying core type for a given type. 
    /// </summary> 
    /// <param name="typ">Type to evaluate.</param> 
    /// <returns>Type.</returns> 
    private static Type GetCoreType(Type typ) 
    { 
     if (typ != null && IsNullable(typ)) 
     { 
      if (!typ.IsValueType) 
      { 
       return typ; 
      } 
      else 
      { 
       return Nullable.GetUnderlyingType(typ); 
      } 
     } 
     else 
     { 
      return typ; 
     } 
    } 

    /// <summary> 
    /// Determines whether the type provided is nullable. 
    /// </summary> 
    /// <param name="typ">Type to evaluate.</param> 
    /// <returns>True if is nullable else false.</returns> 
    private static bool IsNullable(Type typ) 
    { 
     return !typ.IsValueType || (typ.IsGenericType && typ.GetGenericTypeDefinition() == typeof(Nullable<>)); 
    } 

    /// <summary> 
    /// Converts a generic list of type T into a data table. 
    /// </summary> 
    /// <typeparam name="T">The type the list consists of.</typeparam> 
    /// <param name="items">Generic list being extended.</param> 
    /// <returns>DataTable representing the strongly typed list.</returns> 
    public static DataTable ToDataTable<T>(this Collection<T> items) 
    { 
     if (!object.Equals(items, null)) 
     { 
      using (DataTable data = new DataTable(typeof(T).Name)) 
      { 
       data.Locale = System.Globalization.CultureInfo.CurrentCulture; 
       PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 

       foreach (PropertyInfo prop in properties) 
       { 
        data.Columns.Add(prop.Name, GetCoreType(prop.PropertyType)); 
       } 
       foreach (T item in items) 
       { 
        object[] values = new object[properties.Length]; 

        for (int i = 0; i < properties.Length; i++) 
        { 
         values[i] = properties[i].GetValue(item, null); 
        } 
        data.Rows.Add(values); 
       } 
       return data; 
      } 
     } 
     return null; 
    } 

    #endregion 
} 

然后可以合并使用.Merge()方法在一起的两个数据表。

+0

谢谢先生。我完全想要这种类型的代码。 – social 2013-04-10 11:19:39