【问题标题】:exception when assigning currentcell datagridview分配 currentcell datagridview 时的异常
【发布时间】:2012-12-01 05:37:24
【问题描述】:

我有一个非常奇怪的例外。我有一个 datagridview 绑定到一些数据。当数据源为空时,我向其中添加一些数据,更新 datagridview 并尝试将我添加的行设置为编辑模式。代码如下:

foreach (DataGridViewRow row in dataGridViewActionTemplates.Rows)
{
    if (((GridActionTemplate)row.DataBoundItem).ID == actTemplate.Id)
    {
        dataGridViewActionTemplates.CurrentCell = row.Cells[dataGridViewActionTemplates.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Index];
        dataGridViewActionTemplates.BeginEdit(false);
        break;
    }
 }

当我尝试执行分配时,我得到一个“IndexOutOfRange”异常,它说“索引 -1 没有值。”这很奇怪,因为赋值右侧的索引大于零。

非常感谢您的帮助

【问题讨论】:

  • 把这个放到一个Int32变量dataGridViewActionTemplates.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Index中然后在Cells[myVariable]中引用,现在的值是多少?
  • ' int CellIndex = dataGridViewActionTemplates.Columns.GetFirstColumn(DataGridViewElementStates.Visible).Index;' CellIndex 是 1。这就是为什么我不明白它是如何工作的
  • 这应该没什么区别,但是如果你硬编码 1、2 或 3,你会得到同样的异常吗?
  • 是的。我的第一列是不可见的,因此 CellIndex=0 抛出异常“无法设置为不可见行”,当我超出 ColumnCollection 时,我得到“索引超出范围。必须为非负数且小于集合的大小。 "
  • 在相关说明中,我得到了一个索引越界异常,因为在为 currentcell 分配任何单元格的值时,它触发了我的 selectionchanged 事件,尽管我的异常可能存在一些问题提到了那个方法,我怀疑你的情况就是这样。

标签: c# winforms data-binding datagridview


【解决方案1】:

我记得遇到了一些类似的奇怪现象,我最终发现这与在 Windows 7 中选择的 Windows 主题有关。当时我的代码在 Aero 上正常工作,没有任何例外,但在 Win 中启用 Classic 主题时,其行为与您的相似7或当代码在Windows 2003上运行时。情况与您的情况不完全相同,所以我不知道是否是相同的问题,但这可能是值得关注的一件事。具体问题与列标题和行标题的索引有关,奇怪的是它们在 2 个不同的主题中返回的值不同。也就是说,可能是您在不知不觉中尝试修改行标题字段而不是第一个实际数据字段。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 2012-07-23
    相关资源
    最近更新 更多