如何在没有任何数据源的情况下从DataGridView创建DataTable?

我想从DataGridView获取Grid值的DataTable。

换句话说,DataTable与DataGridView值相同

可能是一个更好的方法,但否则只需循环遍历DGV并手动创建DataTable将是相当微不足道的。

这样的事情可能有用:

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

您可以将DataSource对象从DataGridView转换为DataTable

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

您也可以使用以下代码,当您在数据表中添加或删除行时,此代码填充对DataGridView没有影响

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