单击标题时,DataGridView中的“索引超出范围”异常

时间:2014-10-09 14:19:21

标签: c# winforms datagridview indexoutofrangeexception

我使用DataGridView从SQLite数据库显示我的数据。一列是打开分配给该行的pdf的目录。代码可以工作但是,每次我点击列标题时,它都会给出错误:

  

指数超出范围。必须是非负数且小于集合的大小。

实际上,每当我点击列文本(只是“PDF”或任何其他列的文本)时,它都会抛出该错误。但是当我在文本外面(在订购框中的任何地方)点击时,它会重新排序我的列,这没关系。有什么想法吗?

代码工作,打开PDF,但我不希望用户不小心点击标题文本和程序崩溃。以下是datagridview打开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

1 个答案:

答案 0 :(得分:4)

点击标题时,您获得了例外,因为RowIndex-1。当他们点击标题时你不希望发生任何事情,所以你可以检查那个值并忽略它。

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

此外,FWIW,当您点击标题中的文本因为您订阅了CellContentClick时(仅当您单击单元格的内容时触发,例如文本),您才会获得异常。我建议使用CellClick事件(点击单元格的任何部分时会触发)。