Onl*_*ito 2 c# datagridview winforms indexoutofrangeexception
我正在使用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);
}
}
Run Code Online (Sandbox Code Playgroud)

单击标题时会出现异常,因为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);
}
Run Code Online (Sandbox Code Playgroud)
同样,FWIW,您仅在单击标题中的文本(因为您已订阅)时才会获得异常CellContentClick(仅在单击单元格的内容(例如文本)时触发)。我建议使用CellClick事件(单击单元格的任何部分时触发)。
| 归档时间: |
|
| 查看次数: |
9702 次 |
| 最近记录: |