3

我正在使用 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);
        } 
   }

在此处输入图像描述

4

1 回答 1

7

单击标题时会出现异常,因为RowIndexis -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事件(单击单元格的任何部分时触发)。

于 2014-10-09T14:29:35.550 回答