2017-07-28 47 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