导出datagridview selectedrow到一个数据表中是行不通的

本文关键字:数据表 一个 行不通 selectedrow datagridview 导出 | 更新日期: 2023-09-27 18:17:19

我想从一个datagridview导出所有selectedRows到一个DataTable。当单击(选择)超过2行时,出现下一个错误:

"系统类型的异常错误。在System.Data.dll中发生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显示,只有被选中的drows被保存到一个数据表。

导出datagridview selectedrow到一个数据表中是行不通的

使用下面的简单代码:

var dtSource = dataGridView1.DataSource as DataTable;
var dt = dtSource.Clone();
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
    dt.ImportRow(dtSource.Rows[row.Index]);
}