/ / Exportar datagridview selectedrows para uma tabela de dados não funcionará - c #, datagridview, datatable

Exportar datagridview selectedrows para uma tabela de dados não funcionará - c #, datagridview, datatable

Eu quero exportar todos os selectedRows de um datagridview para um DataTable. Ao clicar (selecionar) em mais de 2 linhas, o próximo erro aparece:

"Ocorreu um erro de exceção do tipo System.IndexOutOfRangeException em System.Data.dll."

Primeiro tentei:

DataTable table = new DataTable();
for (int i = 0; i < dataGridView_auswahlen.Rows.Count; i++) {
if (dataGridView_auswahlen.Rows[i].Selected) {
table.Rows.Add( );
for (int j = 0; j < dataGridView_auswahlen.Columns.Count; j++) {
table.Rows[i][j] = dataGridView_auswahlen[j, i].Value;
}
}
}

Depois disso, eu o modifiquei em:

DataTable dt = new DataTable(); // create a table for storing selected rows
var dtTemp = dataGridView1.DataSource as DataTable; // get the source table object
dt = dtTemp.Clone();  // clone the schema of the source table to new table
DataTable table = new DataTable();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
var row =   dt.NewRow();  // create a new row with the schema
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
row[j] = dataGridView1[j, i].Value;
}
dt.Rows.Add(row);  // add rows to the new table
}
}

O problema agora é que o meu dataGridView está exibindo apenas 1 resultado. Eu preciso ter a lista de resultados completa no meu dataGridView exibido e apenas o selectedrows para ser salvo em um DataTable.

Respostas:

1 para resposta № 1

Use este código simples:

var dtSource = dataGridView1.DataSource as DataTable;
var dt = dtSource.Clone();

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dt.ImportRow(dtSource.Rows[row.Index]);
}