导入excel文件并将DataGridView选定的行显示到另一个DataGridView

时间:2016-07-31 01:05:47

标签: c# excel winforms datagridview

我正在尝试导入excel文件并将其加载到我的datagridview1

DataGridView中显示文件内容后,我想选择该行并将其转移到我的第二个DataGridView

请有人可以帮我解决我的代码问题吗?因为我收到了错误:

  

System.Windows.Forms.dll中出现未处理的“System.InvalidOperationException”类型异常

private void button1_Click(object sender, EventArgs e)
{
   string PathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +textBox1.Text + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + "Sheet1" + "$]", conn);
   DataTable dt = new DataTable();
   myDataAdapter.Fill(dt);
   dataGridView1.DataSource = dt;
}
private void button2_Click(object sender, EventArgs e)
{
   OpenFileDialog openFileDialog1 = new OpenFileDialog();
   if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
   {
   this.textBox1.Text = openFileDialog1.FileName;
   }
}
private void button3_Click(object sender, EventArgs e)
{
   foreach (DataGridViewRow selRow in dataGridView1.SelectedRows.OfType<DataGridViewRow>().ToArray())
   {
   dataGridView2.Rows.Remove(selRow);
   dataGridView2.Rows.Add(selRow);
   }
}

1 个答案:

答案 0 :(得分:0)

你可以尝试更像这样的东西

var selected_rows = new List<DataGridViewRow>();
foreach (DataGridViewRow selRow in dataGridView1.SelectedRows.OfType<DataGridViewRow>().ToArray())
{
      selected_rows.Add(row);
}
foreach(var row in selected_rows){
      dataGridView1.Rows.Remove(row);
      dataGridView2.Rows.Add(row);
}

C#通常不允许在枚举该集合时修改集合。您通常可以通过使用初始循环来简单地收集您希望操作的对象来解决此问题,然后您可以遍历该对象集合。像这样的东西

我还想象调用dataGridView1.SelectedRows就足够了。没有必要转换为强类型数组,但这可能更像是一种语法偏好。

尝试一下,让我知道它是如何工作的