我的表单中有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 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 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;
}
甚至,我有行和列索引:datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value
仍无效。
答案 0 :(得分:1)
尝试添加此活动
dgv.DataError += new DataGridViewDataErrorEventHandler(dgv_DataError);
void dgv_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
//Show any message or not.. its upto you now
}
修改:
将您的cellvalidating事件修改为
private void datagridview_CellValidating(object sender, CellValidatingEventArgs e)
{
try
{
int temp = Convert.ToInt32(e.Value.ToString())
if(temp < -5000 || temp > 5000)
datagridview.Rows[e.RowIndex].ErrorText = "The value must be bteewn 5000 and 5000";
}
catch
{
datagridview.Rows[e.RowIndex].ErrorText = "The value must be integer and bteewn 5000 and 5000";
}
}