我在我的表單中有2個Datagridview,我在使用細胞驗證和細胞驗證事件處理程序..在我的datagridview。如果我將光標放在單元格本身中,並嘗試通過菜單點擊打開一個新文件。我收到一條錯誤消息:「異常的參數未被用戶代碼處理,索引超出範圍。」CellValidating細胞焦點錯誤
我知道,當光標在單元格中時,它得到了焦點,它在單元驗證過程中,這就是爲什麼我得到這個錯誤。
此行引發錯誤消息:「異常的參數未被用戶代碼處理,索引超出範圍。」 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;
}
}
菜單項的Clik打開新文件到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事件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;
}
即使,我有行和col索引:datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value
仍然無法正常工作。
你嘗試data_error事件? – Sami
@Sami:不...是否真的與我的問題有關。請向我解釋。 – linguini
不要在dataerror事件中顯示任何錯誤,請嘗試修改(通過我)cellvalidating代碼。似乎有問題,如果條件的層次結構。儘管聚焦的細胞中有有效的值,你是否得到了錯誤?希望不是。如果是,那麼你在其他地方有問題。這可能需要更多關於你的代碼和場景的信息 – Sami