Index out of range exception in datagridview when header is selected

喜夏-厌秋 提交于 2019-12-25 10:56:04

问题


I have a datagridview that when I click on a header to sort or for any reason I get the follow error on the following line of code....

Argument our of range exception (Index was out of range. Must be non negative and less than the size of the collection.

 private void firearmView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
            //I get the above error on the IF line below.
            if (!firearmView.Rows[e.RowIndex].IsNewRow) 
            {
                selectedFirearmPictureBox.Image = Image.FromFile(firearmView.Rows[e.RowIndex].Cells[12].Value.ToString(), true);
            }

    }

I do not know why I am getting this particular error here.


回答1:


The MSDN says in the docs about RowIndex property

When the RowIndex property returns -1, the cell is either a column header, or the cell's row is shared.

So you need to handle the e.RowIndex == -1 when you receive the event
(...The index must not be negative....)

private void firearmView_CellClick(object sender, DataGridViewCellEventArgs e)
{

    if(e.RowIndex == -1) return;

    if (!firearmView.Rows[e.RowIndex].IsNewRow) 
    {
        selectedFirearmPictureBox.Image = Image.FromFile(firearmView.Rows[e.RowIndex].Cells[12].Value.ToString(), true);
    }
}


来源:https://stackoverflow.com/questions/24945342/index-out-of-range-exception-in-datagridview-when-header-is-selected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!