获得“索引超出范围".单击标题时DataGridView中的异常 [英] Getting "Index was out of range" exception in DataGridView when clicking header

查看:319
本文介绍了获得“索引超出范围".单击标题时DataGridView中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用DataGridView来显示来自SQLite数据库的数据.一栏是打开分配给该行的pdf的目录.该代码有效,但是每次我单击列标题时,都会出现错误:

I am using a DataGridView to display my data from a SQLite database. One column is a directory to open pdfs assigned to the row. The code works but, every time I click on the column title, it gives me the error:

索引超出范围.必须为非负数,并且小于集合的大小.

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

实际上,每当我单击列文本(只是"PDF"或任何其他列的文本)时,都会引发该错误.但是,当我在文本外部(在排序框中的任意位置)单击时,它会重新排列我的列,这没关系.有什么想法吗?

Actually, any time I click the column text (just "PDF", or any other column's text) it throws that error. But when I click outside the text (anywhere in the ordering box), it reorders my columns, which is ok. Any ideas?

该代码有效,打开了PDF,但我不希望用户意外单击标题文本而导致程序崩溃.这是datagridview打开pdf的代码.

The code works, opens up the PDF, but I don't want the user accidentally clicking the title text and the program crash. Here is the code for the datagridview to open the 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);
        } 
   }

推荐答案

单击标题时会出现异常,因为RowIndex-1.当他们单击标题时,您不希望发生任何事情,因此您可以检查该值并忽略它.

You're getting the exception when you click the header because the RowIndex is -1. You don't want anything to happen when they click the header anyway, so you can check for that value and ignore it.

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事件(单击单元格的任何部分时触发).

Also, FWIW, you're only getting the exception when you click the text in the header because you subscribed to CellContentClick (only fires when you click the content of the cell, such as the text). I'd suggest using the CellClick event (fires when any part of the cell is clicked).

这篇关于获得“索引超出范围".单击标题时DataGridView中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆