2009-09-06 32 views
1

下面的代碼引發了一個InvalidOperationException與上面的消息,我不明白爲什麼。當用戶可能對datagridview的底層數據源進行了更改時,我的代碼調用以下方法。目標是使用任何更改的數據更新顯示,並保留排序列和順序。只能對屬於DataGridView控件的單元格執行操作

 
private void ReloadDataGridBindingListFromDatabase() 
     { 
      DataGridView dgv = myDataGridViewControl; 
      DataGridViewColumn sortedColumn = dgv.SortedColumn; 
      SortOrder sortOrder = dgv.SortOrder; 

      //do stuff here to refresh dgv.DataSource 

      if (sortedColumn != null) 
      { 
       //this line throws an exception 
       sortedColumn.HeaderCell.SortGlyphDirection = sortOrder; 
      } 

      //etc. 
     } 

顯然,sortedColumn.HeaderCell是屬於DataGridView控件的單元格。那麼,爲什麼我會得到這個異常?

非常感謝您的意見。

回答

1

沒關係。我很清楚,重新綁定datagridview的數據源會破壞datagridview中的所有列並創建新的列。所以我不能堅持重新綁定的列參考。

2

我就遇到了這個錯誤時: 使用Microsoft樣本DataGridViewAutoFilterColumnHeaderCell和 在OnLoad事件窗口的設置DataGridViewDataSource

如果您將DataGridView綁定到DataTable,並且DefaultView的排序條件包括DataGridViewAutoFilterColumn之一,則會出現此錯誤。

因此,要在設置DataSource之前解決該問題,請清除DataTableDefaultView的排序順序。

如:

// Without this line if the sort included a column that is an 
// auto filter column you will get an error 
table.DataView.Sort = ""; 

dataGridView.DataSource = new BindingSource(table, null); 

====================

我嘗試了上述建議的解決方案 - 它沒有爲我工作確切地說,但它使我走上了正確的軌道。我提供我的(非常相似的)解決方案。

myBindingSource.DataSource = myAlreadyFilledDataTable 
    myBindingSource.RemoveSort() 
    myDataGridView.DataSource = myBindingSource 
相關問題