2015-05-02 39 views
1

我的datagrid视图填充了多行数据,我希望能够在我的datagridview中选择多行,然后更新datagridview只显示选定的行,但我收到错误C#DATAGRIDVIEW选择行并显示选定的行

public void btnUpdate_Click(object sender, EventArgs e) 
    { 


     List<DataGridViewRow> rowCollection = new List<DataGridViewRow>(); 
     foreach (DataGridViewRow row in dataGridView1.SelectedRows) 
     { 
      rowCollection.Add(dataGridView1.Rows[row.Index]); 
     } 

     //dataGridView1.Rows.Clear(); 




    data.Tables[0].Clear(); 


     foreach (DataGridViewRow row in rowCollection) 
     { 
      DataRow r = data.Tables[table].NewRow(); 
      dataGridView1.Rows.Add(row); 
      //write the data in the DataRow and then add the datarow in your datatable 
      data.Tables[table].Rows.Add(r); 


     } 
     CreateGraph(zedGraphControl1); 





    } 

当我选择行并点击更新按钮我得到的错误 “行不能被编程方式添加到DataGridView的行集合时,该控件是数据绑定的。”

  • 行{{的DataGridViewRow指数= -1}} System.Windows.Forms.DataGridViewRow

我试图寻找这个异常的帮助,但无法理解它 感谢您的帮助

+0

如果DGV是数据绑定的,您可以设置'DataSource = null'来解除绑定。尝试清除桌子时。 –

+1

另外,请记住* SelectionMode属性必须设置为'FullRowSelect'或'RowHeaderSelect'为'SelectedRows'属性填充选定的行。* –

+0

@steve我尝试过使用该方法,但它删除了datagrid视图中的所有值,包括列名 – FlipperFlapper

回答

1

如果我没记错的话,datagridview不能被数据绑定以操纵行。

我相信几个月前我解决了这个问题,但是现在我无法访问我的项目。

我想你可以通过从数据源中查找并删除行做到这一点,然后刷新DataGridView的

(个人建议:暂时休息10-15分钟,并回到它提供了更清晰的头脑)

+0

你说的是对的,我已经看到了我以前掠过的东西 – FlipperFlapper