How to make a DataTable from DataGridView without any Datasource?

前端 未结 3 832
野性不改
野性不改 2020-12-03 14:57

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

In other words DataTable same as DataGridView Values

3条回答
  •  死守一世寂寞
    2020-12-03 15:24

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

提交回复
热议问题