c# - 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;
我试图避免循环解决方案。希望有人知道如何解决这个问题。谢谢!
解决方案
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;
}
推荐阅读
- sql - 是否可以将登录用户添加到只读数据库?
- javascript - React hooks map 不是函数
- android - Crashlytics 不发送崩溃报告,而是显示带有错误消息的红屏
- python - 考拉 pip 安装在 pyarrow 依赖项上失败
- debian - 错误 503 centeron 如何正确重定向
- kubernetes - 从副本集中的特定容器获取所有日志
- java - 如何解决fabric-sdk-java中的“实例化链码”错误?
- scala - sbt-native-packager:Alpine Docker Image 上的 Scala 应用程序失败,权限被拒绝
- php - 回显 20 到 1000 之间的奇数,并使用 php 将数字 23、33、43、63、193、213、333、453、693、793、813、883、963 加粗
- python - 尝试第二次运行时 Python tkinter 应用程序崩溃