【问题标题】:Collection to DataTable收集到数据表
【发布时间】:2015-04-13 15:20:55
【问题描述】:

我正在尝试将 Collection 转换为 DataTable,以便可以将其绑定到 gridview。 (如果有其他方法,我愿意接受)

这就是集合的样子:

public class CustomerCollection 
{
    [JsonProperty("customer")] 
    public IEnumerable<customer> Customer { get; set; } 
}

public class customer  
{ 
    [JsonProperty("customer-name")] 
    public string strCustomerName { get; set; } 
    [JsonProperty("customer-address")] 
    public List<string> lCustomerAddress { get; set; } 
}

最终结果如下所示:

我在尝试将其绑定到 gridview 时遇到的问题。我收到如下错误:

Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.

当使用 Helper 类尝试将其转换为 DataTable 时,我得到:

The type arguments for method 'CollectionHelper.ConvertTo<T>(System.Collections.Generic.IList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

【问题讨论】:

    标签: c# gridview collections datatable converter


    【解决方案1】:

    您应该将您的网格视图绑定到 Customer 集合属性:

    gvDisplay.DataSource = customers.Customer;
    

    您的代码不起作用的原因是因为您将它直接绑定到 customers 类型为 CustomerCollection 的变量,而该变量(尽管它的名称)根本不是一个集合,它只是一个带有 Customer 属性的简单 .NET 类。

    【讨论】:

    • 您可能会为您的类和属性找到更好的命名方式,因为它们非常容易产生误导。例如,CustomerCollection 类可能应该命名为CustomerDataCustomer 属性可能应该命名为Customers,因为它是customer 的集合。
    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多