2013-02-07 69 views
2

我正在開發一個帶有datagridview的表單。更改單元格中的當前單元格輸入DataGridView的事件

我想要的結果是:

  • 當用戶點擊只讀細胞,將光標移動到可編輯單元。
  • 當用戶單擊可編輯單元格時,光標將位於此當前可編輯單元格上。

我使這Cell_Enter Event(我有一定的理由代碼Cell_Enter我必須使用Cell_Enter)。

DataGridViewCell cell = myGrid.Rows[cursorRow].Cells[cursorCol]; 
myGrid.CurrentCell = cell; 
myGrid.BeginEdit(true); 

點擊Editable Cell是OK,點擊ReadOnly Cell給出一個異常錯誤:因爲它導致折返調用SetCurrentCellAddressCore功能

錯誤 - > 操作無效。

那麼,是否有解決這個問題的方法? (當用戶點擊ReadOnly Cell,將光標移動到Editable細胞)

編輯:我想解決的辦法是如何將光標移動到其他細胞,是不是當前單元格?

+0

也許你可以做一個'SendKeys.Send(「{TAB}」);'在單元格爲只讀的情況下 – V4Vendetta

回答

2

我已經發現了這個問題here的解決方案。


 private void myGrid_CellEnter(object sender, DataGridViewCellEventArgs e) 
     { 
      //Do stuff 
      Application.Idle += new EventHandler(Application_Idle); 

     } 

     void Application_Idle(object sender, EventArgs e) 
     { 
      Application.Idle -= new EventHandler(Application_Idle); 
      myGrid.CurrentCell = myGrid[cursorCol,cursorRow]; 
     } 
+0

非常好;)謝謝 –

1

嘗試使用If.. else ..statement

if (cursorCol == 1) //When user clicks on ReadOnly Cell, the Cursor will move to Editable Cell. 
{ 
    myGrid.CurrentCell = myGrid[cursorRow, cursorCol]; 
} 
else //When user clicks on Editable Cell, the Cursor will be on this Current Editable Cell. 
{ 
    //Do stuff 
    myGrid.BeginEdit(true); 
} 
+0

我想要的解決方案是如何將光標移動到不是當前單元格的其他單元格? – nnnn

+0

我更新了我的答案。 – spajce

+0

它給出同樣的錯誤。 – nnnn

1

我不是100%肯定這會在你的情況下工作,但有一次我碰到了因客戶的愚蠢的UI要求之一是這樣的。快速解決方案是將代碼包裝在BeginInvoke中。例如:

BeginInvoke((Action)delegate 
{ 
    DataGridViewCell cell = myGrid.Rows[cursorRow].Cells[cursorCol]; 
    myGrid.CurrentCell = cell; 
    myGrid.BeginEdit(true); 
}); 

本質上講,這將使其成爲CellEnter事件後執行的代碼,允許DataGridView做任何它認爲是導致異常的幕後。

最終它被重構爲一個自定義控件,擴展了DataGridViewBeginInvoke不再需要。

+0

感謝您的關注。此答案可能會解決問題,但我已經在昨天晚上找到解決方案,回答。明天我會接受它作爲答案。 – nnnn

相關問題