将DataGrid视图转换为DataSet/DataTable的最佳方式

本文关键字:DataTable 最佳 方式 DataSet DataGrid 视图 转换 | 更新日期: 2023-09-27 17:57:41

DataSetDataTablelinq表达式DataGridView的常见DataSource值。

现在反过来,是否可以将DataGridView记录传递/绑定到DataSetDataTable

感谢

将DataGrid视图转换为DataSet/DataTable的最佳方式

您可以这样做:

var dataTable = new DataTable();
Array.ForEach(
    dataGridView1.Columns.Cast<DataGridViewColumn>().ToArray(), 
    arg => dataTable.Columns.Add(arg.HeaderText, arg.ValueType));
Array.ForEach(
    dataGridView1.Rows.Cast<DataGridViewRow>().ToArray(), 
    arg => dataTable.Rows.Add(arg.Cells.Cast<DataGridViewCell>().Select(cell => cell.Value)));
return dataTable;

你可以试试这个:

Public Shared Function DataGridViewToDataTable(ByVal dtg As DataGridView,
    Optional ByVal DataTableName As String = "myDataTable") As DataTable
    Try
        Dim dt As New DataTable(DataTableName)
        Dim row As DataRow
        Dim TotalDatagridviewColumns As Integer = dtg.ColumnCount - 1
        'Add Datacolumn
        For Each c As DataGridViewColumn In dtg.Columns
            Dim idColumn As DataColumn = New DataColumn()
            idColumn.ColumnName = c.Name
            dt.Columns.Add(idColumn)
        Next
        'Now Iterate thru Datagrid and create the data row
        For Each dr As DataGridViewRow In dtg.Rows
            'Iterate thru datagrid
            row = dt.NewRow 'Create new row
            'Iterate thru Column 1 up to the total number of datagrid columns
            For cn As Integer = 0 To TotalDatagridviewColumns
                row.Item(cn) = dr.Cells(cn).Value
            Next
            'Now add the row to Datarow Collection
            dt.Rows.Add(row)
        Next
        'Now return the data table
        Return dt
    Catch ex As Exception
        Return Nothing
    End Try
End Function

摘录自本网站:http://www.sourcehints.com/articles/how-to-convert-datagridview-data-to-datatable.html

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

示例:要使用此方法,只需使用以下代码示例:

var vrCountry = from country in objEmpDataContext.CountryMaster
                select new {country.CountryID,country.CountryName};
DataTable dt = LINQToDataTable(vrCountry);

感谢