使用VB / C#.NET中的DataGridView数据填充数据表

时间:2010-12-02 04:57:04

标签: c# .net vb.net datagridview datatable

如何使用DataGridView数据(VB / C#.NET)填充Datatable?

1 个答案:

答案 0 :(得分:5)

假设它是Winform

下面的代码可以提供帮助

        //dgv is the name of your data grid view.

        DataTable dt = new DataTable();
        DataColumn[] dcs = new DataColumn[]{};

        foreach (DataGridViewColumn c in dgv.Columns)
        {
            DataColumn dc = new DataColumn();
            dc.ColumnName = c.Name;
            dc.DataType = c.ValueType;
            dt.Columns.Add(dc);

        }

        foreach (DataGridViewRow r in dgv.Rows)
        {
            DataRow drow = dt.NewRow();

            foreach (DataGridViewCell cell in r.Cells)
            {
                drow[cell.OwningColumn.Name] = cell.Value;
            }

            dt.Rows.Add(drow);
        }