2015-05-02 42 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