DataGridView选择了行到DataTable

时间:2013-10-28 16:06:05

标签: c# winforms datagridview datatable selection

我正在尝试仅将DataGridView的选定行添加到DataTable中,我使用的代码总是从第一行开始,即使没有选择这一行...是否有人知道如何要解决这个问题吗?

 DataTable dt = new DataTable("Rapport");

            //Generating columns to datatable:
            foreach (DataGridViewColumn column in dataGridView1.Columns)
                dt.Columns.Add(column.Name, typeof(string));

            //Adding selected rows of DGV to DataTable:
            for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
            {
                dt.Rows.Add();
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    dt.Rows[i][j] = dataGridView1[j, i].Value;
                }
            }

3 个答案:

答案 0 :(得分:11)

您必须访问SelectedRows之类的

dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;

如果您的DataTable与Cell

的类型相同,也会更好
DataTable dt = new DataTable();
 foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type

所以你的代码是:

DataTable dt = new DataTable();
foreach (DataGridViewColumn column in dataGridView1.Columns)
    dt.Columns.Add(column.Name, column.CellType); //better to have cell type
for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
{
     dt.Rows.Add();
     for (int j = 0; j < dataGridView1.Columns.Count; j++)
     {
         dt.Rows[i][j] = dataGridView1.SelectedRows[i].Cells[j].Value;
                                   //^^^^^^^^^^^
     }
 }

答案 1 :(得分:0)

DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
                foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
                {
                    dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
                }
                dt.AcceptChanges();

答案 2 :(得分:0)

感谢您的代码非常有帮助