我的表单中有 2 个 Datagridview,我在我的 datagridview 中使用单元格验证和单元格验证事件处理程序。如果我将光标留在单元格本身并尝试通过菜单单击打开一个新文件..我收到一条错误消息:“用户代码未处理异常参数,索引超出范围。”
我知道,当光标位于单元格中时,它会获得焦点并且它正在单元格验证过程中,这就是我收到此错误的原因。
此行引发错误消息:“用户代码未处理异常参数,索引超出范围。”
datagridview.Rows[e.RowIndex].ErrorText = "";
我怎样才能避免这个错误?或者如何在菜单单击打开新文件时移除焦点?谢谢你。
private void datagridview_CellValidating(object sender, CellValidatingEventArgs e)
{
if (e.ColumnInfo.Name == "Item1" || e.ColumnInfo.Name == "Item2")
{
datagridview.Rows[e.RowIndex].ErrorText = "";
int newInteger;
if (datagridview.Rows[e.RowIndex].IsModified)
return;
if (!int.TryParse(e.Value.ToString(),
out newInteger) || newInteger < -50000 || newInteger > 50000)
{
e.Cancel = true;
datagridview.Rows[e.RowIndex].ErrorText = "The value must be a non-negative integer";
}
}
}
private void datagridview_CellValidated(object sender, CellValidatedEventArgs e)
{
if (e.ColumnIndex != 3)
return;
int nextRowIndex = e.RowIndex + 1;
int lastRowIndex = datagridview.Rows.Count - 1;
if (nextRowIndex <= lastRowIndex)
{
var value = datagridview.Rows[e.RowIndex].Cells[3].Value.ToString();
datagridview.Rows[nextRowIndex].Cells[2].Value = value;
}
}
MenuItem 点击打开新文件到 Datagridview:
private void m_test1_Click_1(object sender, EventArgs e)
{
myconfig = Myconfig.DeserializeFromXmlFile(@"test2.xml");
Display(rseConfig);
m_ConfigPages.Visible = true;
}
private void m_test2_Click(object sender, EventArgs e)
{
myconfig = Myconfig.DeserializeFromXmlFile(@"test2.xml");
Display(myconfig );
m_ConfigPages.Visible = true;
}
我正在使用 DataError Event Hnadler,但它不起作用:
private void datagridview_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
// Don't throw an exception when we're done.
e.ThrowException = false;
// Display an error message.
string txt = "Error with " +
datagridview.Columns[e.ColumnIndex].HeaderText +
"\n\n" + e.Exception.Message;
MessageBox.Show(txt, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// If this is true, then the user is trapped in this cell.
e.Cancel = true;
}
甚至,我有 row 和 col 索引:datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value
仍然无法正常工作。