简体   繁体   English

C# Gridview 数据源到数据表

[英]C# Gridview datasource to datatable

I'm trying to convert a gridview datasource to a datatable.我正在尝试将 gridview 数据源转换为数据表。

What I have tried so far到目前为止我尝试过的

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

Also I have tried this我也试过这个

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;

And this和这个

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

I'm populating my gridview in the following way我正在按以下方式填充我的 gridview

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

I'm trying to avoid loop solutions.我试图避免循环解决方案。 Hope someone has an idea how to solve this.希望有人知道如何解决这个问题。 Thanks!谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM