![](/img/trans.png)
[英]How to bind a new datatable to a gridview which already has an old datatable
[英]How to Rebind Listview which is already bind with a datatable
我有一个Listview
,其中有一个DataTable
作为DataSource
。 现在,我想将其与通用列表重新绑定。 之后,将同时Listview
数据, DataTable
和Generic列表数据。 可能吗?
与DataTable
绑定的Listview
有3条记录。 现在,我在Listview
之外有一个Add Button,并在Add Button Click上的Generic List中添加了一条新记录,然后我暂时想将此新记录与Listview1一起显示。 最后,我在FinalSubmit的单击上添加了此新记录。
如果我正确理解了这一点,那么您想组合两种不同的数据类型并将它们本质上合并为一种,以便可以将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()方法将两个数据表合并在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.