Getting “Index was out of range” exception in DataGridView when clicking header

江枫思渺然 提交于 2019-12-06 09:30:19

You're getting the exception when you click the header because the RowIndex is -1. You don't want anything to happen when they click the header anyway, so you can check for that value and ignore it.

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex == -1 || e.ColumnIndex != 3)  // ignore header row and any column
        return;                                  //  that doesn't have a file name

    var filename = dataGridView1.CurrentCell.Value.ToString();

    if (File.Exists(filename))
        Process.Start(filename);
}

Also, FWIW, you're only getting the exception when you click the text in the header because you subscribed to CellContentClick (only fires when you click the content of the cell, such as the text). I'd suggest using the CellClick event (fires when any part of the cell is clicked).

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