2016-11-11 64 views
0

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

“在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中。

回答

1

使用这个简单的代码:

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

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

这救了我一吨的麻烦。 – schizoid04