我已经创建了列并从数据库检索到数据以填充DataGridView
。C#DataGridView:禁用列的CellEnter事件
我有一个CellEnter
事件触发并处理选定的网格行。但是,DataGridViewColumn
也会触发CellEnter
,当我单击列标题对数据进行排序时,程序会尝试处理它并引发ArgumentOutOfRange
异常。
如何禁用为列调用CellEnter?
我已经创建了列并从数据库检索到数据以填充DataGridView
。C#DataGridView:禁用列的CellEnter事件
我有一个CellEnter
事件触发并处理选定的网格行。但是,DataGridViewColumn
也会触发CellEnter
,当我单击列标题对数据进行排序时,程序会尝试处理它并引发ArgumentOutOfRange
异常。
如何禁用为列调用CellEnter?
我以前遇到类似的情况。以下为我工作。
此示例说明如何避免在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;
}
Stephen,感谢您的编辑。在我的答案的文本部分中提到突出显示的方法名称,是“内联代码”标记吗? – JimOfTheNorth
为什么不检查e.rowindex? – TaW