【问题标题】:C# Gridview datasource to datatableC# Gridview 数据源到数据表
【发布时间】:2021-08-01 03:02:54
【问题描述】:

我正在尝试将 gridview 数据源转换为数据表。

到目前为止我已经尝试过什么

dt = (DataTable)GridCanvas.DataSource; // Unable to cast object of type 'System.Collections.Generic.List`1 to type 'System.Data.DataTable'

我也试过了

Unable to cast object of type 'System.Collections.Generic.List`1[CRM.Models.Leads]' to type 'System.Windows.Forms.BindingSource'
BindingSource bindingSource = (BindingSource)GridCanvas.DataSource;
                dt = (DataTable)bindingSource.DataSource;

还有这个

 'Object reference not set to an instance of an object.'
  dt = GridCanvas.DataSource as DataTable;

我正在按以下方式填充我的网格视图

 var dispatchLeads = await API.Zelkon.Leads.Dispatch.Leads(Variables.Agent.username);
        GridCanvas.DataSource = dispatchLeads;

我试图避免循环解决方案。希望有人知道如何解决这个问题。谢谢!

【问题讨论】:

  • await API.Zelkon.Leads.Dispatch.Leads 返回一个通用列表 (CRM.Models.Leads) 你不能将列表转换为这样的数据表;表有列和行。您需要创建一个包含所需列的数据表,然后将列表中的所有对象添加到数据表中。
  • 投射到列表 而不是 DataTable。
  • 你能举个例子吗?
  • @Codexer 也许我没有正确解释自己,数据已经在gridview的数据源中。现在我想将其提取到数据表中
  • 我知道你想要DataTable,请再次阅读我的评论。

标签: c# gridview datatable telerik datasource


【解决方案1】:
 First get the List<Leads> from GridCanvas as 
 List<Leads> data=(List<Leads>)GridCanvas.DataSource;
 Then Convert the List<Leads> to DataTable as;
 DataTable dt=ToDataTable<Leads>(data);
 use following methods for conversion.
 public static DataTable ToDataTable<T>(List<T> items)
    {
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
            {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
            }
            dataTable.Rows.Add(values);
        }
        //put a breakpoint here and check datatable
        return dataTable;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多