c# - 单击标题时在 DataGridView 中获取 "Index was out of range"异常

标签 c# winforms datagridview indexoutofrangeexception

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

enter image description here

最佳答案

当您单击标题时出现异常,因为 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/

相关文章:

c# - 粗体 TreeView 节点被截断 - 官方修复将不起作用,因为构造函数中的代码

sql - 在 vb.net 中向 datagridview 添加更多行

c# - 将 DataGridView 单元格值转换为 DateTime

c# - 使用字典,如何使用 .Max c# winforms 显示多个最常见的数字

sql - ds.Tables.Rows.Add() 调用一次时生成 3 行

c# - 自动保存 - WPF C#

c# - 如何更改 ClickOnce 中先决条件的下载和安装顺序

c# - Asp.Net Core 3.1 检索数据但未将其保存到数据库中

c# - Linq 性能 : does it make sense to move out condition from query?

c# - 检查我的 Windows 应用程序是否正在运行