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

Onlytito picture Onlytito · Oct 9, 2014 · Viewed 12.7k times · Source

I am using a DataGridView to display my data from a SQLite database. One column is a directory to open pdfs assigned to the row. The code works but, every time I click on the column title, it gives me the error:

Index was out of range. Must be non-negative and less than the size of the collection.

Actually, any time I click the column text (just "PDF", or any other column's text) it throws that error. But when I click outside the text (anywhere in the ordering box), it reorders my columns, which is ok. Any ideas?

The code works, opens up the PDF, but I don't want the user accidentally clicking the title text and the program crash. Here is the code for the datagridview to open the pdf.

  private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
    {
        string filename = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
        if (e.ColumnIndex == 3 && File.Exists(filename))
        {
            Process.Start(filename);
        } 
   }

enter image description here

Answer

Grant Winney picture Grant Winney · Oct 9, 2014

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).