5

我正在尝试仅将 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;
                }
            }
4

2 回答 2

12

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;
                                   //^^^^^^^^^^^
     }
 }
于 2013-10-28T16:13:27.817 回答
1
DataTable dt = ((DataTable)dgvQueryResult.DataSource).Clone();
foreach (DataGridViewRow row in dgvQueryResult.SelectedRows)
{
    dt.ImportRow(((DataTable)dgvQueryResult.DataSource).Rows[row.Index]);
}
dt.AcceptChanges();
于 2015-05-19T14:44:41.480 回答