我正在尝试仅将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;
}
}
答案 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)
感谢您的代码非常有帮助