将 DataGrid 视图转换为 DataSet/DataTable 的最佳方法 [英] Best way in Converting DataGrid View to DataSet/DataTable
本文介绍了将 DataGrid 视图转换为 DataSet/DataTable 的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
DataSet
、DataTable
和 linq 表达式 是 DataGridView
的常见 DataSource
值>.
DataSet
, DataTable
and linq expression are common DataSource
values of a DataGridView
.
现在反过来,是否可以将 DataGridView
记录传递/绑定到 DataSet
或 DataTable
?
Now in reverse, is it possible to pass/bind a DataGridView
record to DataSet
or DataTable
?
谢谢
推荐答案
Got this Best Answer from Csharp 角:
Got this Best Answer from Csharp Corner:
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null)
return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first
// time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) &&
(colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null)==null ? DBNull.Value
: pi.GetValue(rec,null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
示例:要使用此方法,只需使用以下代码示例:
Example: To use this method, just use the following code sample:
var vrCountry = from country in objEmpDataContext.CountryMaster
select new {country.CountryID,country.CountryName};
DataTable dt = LINQToDataTable(vrCountry);
谢谢
这篇关于将 DataGrid 视图转换为 DataSet/DataTable 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文