2014-10-09 161 views
1

我正在使用DataGridView来显示来自SQLite数据库的数据。一列是打开分配给该行的pdf的目录。代码工作,但我每次单击列标题时,它给我的错误:单击标题时DataGridView中出现“索引超出范围”异常

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

其实,任何时候我请单击列文(只是“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

回答

3

你得到当你点击标题,因为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事件(单击任何部分单元时触发)。

+0

谢谢!我知道我必须将rowIndex更改为-1,但我使用&&而不是||以类似的方式,您在我测试其他方式时编写代码。谢谢!像魅力一样工作! – Onlytito 2014-10-09 14:55:33

+0

哎呀!一个小运营商造成了这么多问题。 ;) – 2014-10-09 14:57:44