0

我有Listview一个DataTable作为一个DataSource。现在我想用一个通用列表重新绑定它。之后,Listview数据DataTable和通用列表数据都将被持久化。可能吗?

With DataTableBindingListview有 3 条记录。现在我在外部有一个添加按钮,Listview并且在单击添加按钮时在通用列表中添加了一条新记录,然后我暂时想将这条新记录与 `Listview1. 最后,我在点击 FinalSubmit 时添加了这条新记录。

4

1 回答 1

0

如果我理解正确,您想组合两种不同的数据类型并将它们合并为一种,以便您可以将 ListView 与它绑定?

如果是这样,您必须将两者组合成一个单一类型。您可以使用以下代码将您的通用列表转换为 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() 方法将两个数据表合并在一起。

于 2013-04-10T08:56:26.137 回答