日期:2014-05-17  浏览次数:20711 次

两行超级简单的代码让你的程序直接崩溃,请指出原因!
两行超级简单的代码直接让你的程序崩溃,大家分析一下原因!
datagridview控件的两个时间!
鼠标移动到单元格上默认选中这一行,离开的时候不选中!代码如下:

 private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView.Rows[e.RowIndex].Selected = true;//移入选中整行
        }

        private void dataGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView.Rows[e.RowIndex].Selected = false;//离开之后不选中
        }

程序调试的时候开始的时候还可以运行,但是移出控件再移入的时候直接跳出这个错误:

大家分析一下原因!
DataGridView 控件

------解决方案--------------------

private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1)
        dataGridView.Rows[e.RowIndex].Selected = true;
}
 
private void dataGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1)
        dataGridView.Rows[e.RowIndex].Selected = false;//离开之后不选中
}

------解决方案--------------------
错误提示已经给出原因你了,当数据为空或你鼠标移到列头时索引为-1,索引超出范围。
------解决方案--------------------
你的DataGridView没有数据,而你强行使用-1行。
使用try{}catch{}抛出这个错误就好了。
------解决方案--------------------
引用:

private void dataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex != -1)