【问题标题】:Sorting - headers Exception of DataGridView排序 - DataGridView 的标题异常
【发布时间】:2016-07-09 11:56:03
【问题描述】:

我在 windows 窗体中对 datagridview 的标题进行排序时遇到问题...

这是我在 CellContentClick 上的代码

 private void dgvApprovazione_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
        {//Process link on string
            System.Diagnostics.Process.Start(dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string);
        }
    }

我的数据网格视图结果..

但是当我点击标题列时,我有这个例外:

如何解决?

【问题讨论】:

  • 你应该检查(e.RowIndex>=0)
  • 将实际异常复制到剪贴板并替换上图。我们相信您,您不需要照片证据,并且将来可能遇到问题的人可以使用搜索引擎来查找该错误并找到它;这在照片中是不可能的。

标签: c# winforms datagridview datagridviewcolumn


【解决方案1】:

您应该检查单击的单元格是否不在标题行中,否则当您尝试访问该行的单元格时,您会收到ArgumentOutOfRangeException,因为您尝试获取RowIndex = -1 处的单元格。

索引超出范围。必须是非负数且小于 集合。

你需要检查(e.RowIndex>=0)

【讨论】:

  • 如果点击的单元格是标题行,它应该触发DataGridView.ColumnHeaderMouseClick事件
  • 我认为抛出异常是因为Sorting
  • @J3soon OP 正在尝试处理行中链接的点击事件。 (S)他不想处理对列标题的点击。
  • @J3soon 没问题,您可能会发现答案很有帮助;)
  • 我正在使用 Win 8.1 - CellContetnClick 仅在我单击标题单元格的 Text 时触发。为了确保,我应该在另一个操作系统上测试它或阅读它的源代码。无论如何,通过检查e.RowIndex >=0,您将没有问题。
【解决方案2】:

那是因为您点击的是标题,而不是一行。 CellClick 会同时触发两者,并在您单击标题时传递 -1 的 RowIndex

更改代码以在单击标题时忽略该事件:

private void dgvApprovazione_CellContentClick(object sender, 
DataGridViewCellEventArgs e)
{
    if (e.RowIndex == -1) return;

    if (dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
    {//Process link on string
        System.Diagnostics.Process.Start(dgvApprovazione.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string);
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2023-03-21
    相关资源
    最近更新 更多