我正在使用 DataGridView 来显示来自 SQLite 数据库的数据。一列是用于打开分配给该行的 pdf 的目录。该代码有效,但每次我单击列标题时,都会出现错误:
Index was out of range. Must be non-negative and less than the size of the collection.
实际上,每当我单击列文本(只是“PDF”或任何其他列的文本)时,它都会抛出该错误。但是,当我在文本外部(排序框中的任意位置)单击时,它会重新排序我的列,这没问题。有什么想法吗?
代码有效,打开 PDF,但我不希望用户不小心单击标题文本和程序崩溃。这是用于打开 pdf 的 datagridview 的代码。
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);
}
}
最佳答案
当您单击标题时出现异常,因为 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
事件(在单击单元格的任何部分时触发)。
关于c# - 单击标题时在 DataGridView 中获取 "Index was out of range"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280837/