我想将所有selectedRows从datagridview导出到DataTable。单击(选择)超过2行时,将显示下一个错误:
" System.Data.dll中出现System.IndexOutOfRangeException类型的异常错误。"
首先,我试过了:
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;
}
}
}
之后,我将其修改为:
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
}
}
现在的问题是,我的dataGridView只显示了1个结果。我需要在我的dataGridView中显示完整的结果列表,并且只需要将选定的行保存到DataTable中。
答案 0 :(得分:1)
使用这个简单的代码:
var dtSource = dataGridView1.DataSource as DataTable;
var dt = dtSource.Clone();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
dt.ImportRow(dtSource.Rows[row.Index]);
}