How to make a DataTable from DataGridView without any Datasource?

最后都变了- 提交于 2019-11-26 16:54:46

问题


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

In other words DataTable same as DataGridView Values


回答1:


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



回答2:


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

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



回答3:


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();


来源:https://stackoverflow.com/questions/3109009/how-to-make-a-datatable-from-datagridview-without-any-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!