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

情到浓时终转凉″ 提交于 2019-12-10 10:37:41

问题


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);
        } 
   }


回答1:


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



来源:https://stackoverflow.com/questions/26280837/getting-index-was-out-of-range-exception-in-datagridview-when-clicking-header

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