首页 > 解决方案 > C# Gridview 数据源到数据表

问题描述

我正在尝试将 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;

我正在通过以下方式填充我的gridview

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

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

标签: c#gridviewdatatabletelerikdatasource

解决方案


 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;
    }

推荐阅读