You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForm应用DataGridView点击报错:索引超出范围问题求助

解决DataGridView点击触发ArgumentOutOfRangeException异常问题

问题原因

你遇到的System.ArgumentOutOfRangeException异常,核心原因是操作了不存在的索引:

  • 点击DataGridView表头时,e.RowIndex为-1,无对应行数据
  • 点击空单元格或未选中任何行时,SelectedRows集合为空,直接访问SelectedRows[0]超出范围
  • 单元格索引(如Cells[0]、Cells[1])对应的列不存在,导致索引越界

修复后的代码

在处理点击事件前添加有效性判断,确保操作的行和单元格都有效:

int Key = 0;

private void DepList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // 排除表头点击,确保行索引合法
    if (e.RowIndex < 0)
        return;

    // 获取当前点击的行,避免依赖SelectedRows集合
    DataGridViewRow selectedRow = DepList.Rows[e.RowIndex];

    // 检查单元格是否存在且有值,再赋值给文本框
    if (selectedRow.Cells.Count > 1 && selectedRow.Cells[1].Value != null)
    {
        DepNameTb.Text = selectedRow.Cells[1].Value.ToString();
    }
    else
    {
        DepNameTb.Text = string.Empty;
    }

    // 安全处理Key值,同时添加类型转换校验
    if (string.IsNullOrEmpty(DepNameTb.Text) || selectedRow.Cells[0].Value == null)
    {
        Key = 0;
    }
    else
    {
        int.TryParse(selectedRow.Cells[0].Value.ToString(), out int parsedKey);
        Key = parsedKey;
    }
}

额外优化建议

  • 用列名代替索引(如selectedRow.Cells["DepartmentId"].Value),避免列顺序调整导致代码失效
  • 若需要点击行内任意位置都触发,可将DataGridView的SelectionMode设为FullRowSelect,同时改用CellClick事件(触发范围比CellContentClick更广)

触发的异常信息:
System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')'

内容的提问来源于stack exchange,提问作者Cristi Sfat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:55:27