【问题标题】:Getting "Index was out of range" exception in DataGridView when clicking header单击标题时在 DataGridView 中出现“索引超出范围”异常
【发布时间】:2014-10-09 14:19:20
【问题描述】:

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

【问题讨论】:

    标签: c# winforms datagridview indexoutofrangeexception


    【解决方案1】:

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

    【讨论】:

    • 谢谢!我知道我必须将 rowIndex 更改为 -1,但我使用 && 而不是 ||当我测试其他方式时,您以类似的方式编写代码。谢谢!像魅力一样工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多