背景
我正在使用一个 DataGridView
控件,并在其中添加了下面的处理程序到 DataGridView.CellFormatting
事件,以便使一些单元格中的值更易于人类阅读。这个事件处理程序一直很好地工作,格式化所有值没有问题。
然而,最近我发现一个非常罕见的情况会导致一个不寻常的错误。我的 DataGridView
中的列用于显示项目的到期日期,它始终具有一个 int
值。 0
表示事件永远不会到期,任何其他值都是到期日期的 UTC 时间戳。对应的 MySQL 数据库列不允许为空。当用户从一个具有到期日期的 DataGridView
行移动到另一个具有到期日期的 DataGridView
行(此时一切仍然正常),然后按下重新加载数据的按钮(不发送更新,实质上调用 DataAdapter.Fill()
),程序会生成一个 StackOverflowException
**。
没有递归吗?
对我来说,非常不寻常的是,我看不到递归或无限循环的地方。我添加了一个名为 cellFormatCallCount
的类成员,并在每次调用时递增它,但在抛出异常的时候,调试器显示该 int
的值为 1,这是我所期望的,因为我并没有意识到发生递归。
有人能帮助我吗?
如何查看堆栈跟踪?在 VS2008 中,它显示:
{Cannot evaluate expression because the current thread is in a stack overflow state.}
最好的问候,
Robinson
private int cellFormatCallCount = 0;
private void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
try {
// to format the cell, we will need to know its value and which column its in
string value = "";
string column = "";
// the event is sometimes called where the value property is null
if (e.Value != null) {
cellFormatCallCount++; // here is my test for recursion, this class member will increment each call
// This is the line that throws the StackOverflowException
/* ********************* */
value = e.Value.ToString();
/* ********************* */
column = actionsDataGridView.Columns[e.ColumnIndex].Name;
} else {
return; // null values cannont be formatted, so return
}
if (column == "id") {
// different code for formatting each column
} else if (column == "title") {
// ...
} else {
// ...
}
} finally {
cellFormatCallCount = 0; // after we are done with the formatting, reset our recursion counter
}
}