DataGridView转换为DataTable

时间:2013-04-21 11:24:57

标签: c# datagridview datatable

我正在尝试将DataGridView转换为DataTable,但我找到的所有sollution都没有用。任何的想法?或者我需要使用foreach等吗?

        DataTable d = detailsDataGridView.DataSource as DataTable;// return null table

        DataTable dt = new DataTable();
        dt = (DataTable)detailsDataGridView.DataSource;//doesn't work

        BindingSource bs = new BindingSource();
        bs.DataSource = detailsDataGridView.DataSource;
        DataTable d = (DataTable)(bs.DataSource);//doesn't work

2 个答案:

答案 0 :(得分:1)

<强> EDITED

尝试此方法,这就是您所需要的:

DataTable data = GetDataTableFromDGV(dgvMyMembers);

    private DataTable GetDataTableFromDGV(DataGridView dgv)
    {
        var dt = ((DataTable)dgv.DataSource).Copy();
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            if (!column.Visible)
            {
                dt.Columns.Remove(column.Name);
            }
        }
        return dt;
    }

这是一个简单的2列DataGridView

的快速示例解决方案
DataTable dt = new DataTable();
 dt.Column.Add("column1", typeof(string));
 dt.Column.Add("column2", typeof(string));

foreach(DataGridViewRow dgvR in myDataGridView)
{
  dt.Rows.Add(dgvR.Cells[0].Value, dgvR.Cells[1].Value);
}

答案 1 :(得分:0)

一行快速解决方案。希望这会有所帮助

DataTable dt = (DataTable)dgvR.DataSource;