2017-07-28 45 views
0

我已經創建了列並從數據庫檢索到數據以填充DataGridViewC#DataGridView:禁用列的CellEnter事件

我有一個CellEnter事件觸發並處理選定的網格行。但是,DataGridViewColumn也會觸發CellEnter,當我單擊列標題對數據進行排序時,程序會嘗試處理它並引發ArgumentOutOfRange異常。

如何禁用爲列調用CellEnter?

+1

爲什麼不檢查e.rowindex? – TaW

回答

0

我以前遇到類似的情況。以下爲我工作。

此示例說明如何避免在myCellEnterEvent()中執行的處理導致對myCellEnterEvent的另一個調用。如果允許WasICalledBy()在整個堆棧中運行,並且如果您爲每個幀記錄GetMethod().Name,則會看到導致事件被觸發的所有各種情況,並且可以以最合適的方式篩選這些特定情況你的具體情況。

private myCellEnterEvent(object sender, EventArgs e) 
{ 
    if (WasICalledBy("myCellEnterEvent")) 
     return; 

    // do the things you really want to do here... 
} 

private bool WasICalledBy(string MethodName) 
{ 
    bool MethodFound = false; 
    int StartLevel = 2; // ignore this (WasICalledBy) method and ignore the method that called 
         // WasICalledBy(), so that the caller can determine if it resulted in a call to itself. 

    StackTrace st = new StackTrace(); 
    for (int nFrame = StartLevel; nFrame < st.FrameCount; nFrame++) 
    { 
     if (st.GetFrame(nFrame).GetMethod().Name.ToUpper() == MethodName.ToUpper()) 
     { 
      MethodFound = true; 
      break; 
     } 
    } 
    return MethodFound; 
} 
+0

Stephen,感謝您的編輯。在我的答案的文本部分中提到突出顯示的方法名稱,是「內聯代碼」標記嗎? – JimOfTheNorth