开发者

How to make a DataTable from DataGridView without any Datasource?

开发者 https://www.devze.com 2023-01-04 09:38 出处:网络
I want to get a DataTable from DataGridView of the Grid values. In other words DataTable same as DataGridVi开发者_运维百科ew ValuesMight be a nicer way to do it but otherwise it would be fairly trivi

I want to get a DataTable from DataGridView of the Grid values.

In other words DataTable same as DataGridVi开发者_运维百科ew Values


Might be a nicer way to do it but otherwise it would be fairly trivial to just loop through the DGV and create the DataTable manually.

Something like this might work:

DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dgv.Columns)
{
   dt.Columns.Add(col.Name);    
}

foreach(DataGridViewRow row in dgv.Rows)
{
    DataRow dRow = dt.NewRow();
    foreach(DataGridViewCell cell in row.Cells)
    {
        dRow[cell.ColumnIndex] = cell.Value;
    }
    dt.Rows.Add(dRow);
}


You can cast the DataSource object from the DataGridView to a DataTable

DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;


you can use the following code also, this code fill not effect on your DataGridView when you do some add or delete rows in the datatable

DataTable dt = new DataTable();
dt = Ctype(dataGridView1.DataSource,DataTable).copy();


You can try as follow:

using System.Data;
using System.Windows.Forms;

namespace BLL
{
    public class Class_DataGridview_To_DataTable
    {
        public static DataTable UDF_Convert_DataGridView_To_Datatable(DataGridView ImpGrd)
        {
            DataTable ExportDataTable = new DataTable();
            foreach (DataGridViewColumn col in ImpGrd.Columns)
            {
                ExportDataTable.Columns.Add(col.Name);
            }

            foreach (DataGridViewRow row in ImpGrd.Rows)
            {
                DataRow dRow = ExportDataTable.NewRow();
                foreach (DataGridViewCell cell in row.Cells)
                {
                    dRow[cell.ColumnIndex] = cell.Value;
                }
                ExportDataTable.Rows.Add(dRow);
            }

            return ExportDataTable;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消