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

WinForms中DataGridView获取选中行数据触发ArgumentOutOfRangeException

问题分析与修复方案

核心异常原因

你遇到的ArgumentOutOfRangeException主要来自两个可能的点:

  • 直接访问SelectedRows[0]时,SelectedRows集合为空(无选中行)
  • 使用的单元格索引超出了DataGridView实际的列数

修复步骤

1. 改用事件参数定位当前行,避免依赖SelectedRows

CellContentClick事件的e.RowIndex可以直接获取点击的行索引,比SelectedRows更可靠,同时要先判断索引是否有效:

private void MemberSDGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    // 过滤无效行(比如点击表头行时e.RowIndex为-1)
    if (e.RowIndex < 0 || e.RowIndex >= MemberSDGV.Rows.Count)
        return;

    DataGridViewRow targetRow = MemberSDGV.Rows[e.RowIndex];

    // 逐个赋值时,先检查列索引是否在有效范围内,同时处理null值
    NomTb.Text = targetRow.Cells.Count > 3 ? (targetRow.Cells[3].Value?.ToString() ?? "") : "";
    PrenomTb.Text = targetRow.Cells.Count > 4 ? (targetRow.Cells[4].Value?.ToString() ?? "") : "";
    AgeTb.Text = targetRow.Cells.Count > 6 ? (targetRow.Cells[6].Value?.ToString() ?? "") : "";
    AddressTb.Text = targetRow.Cells.Count > 13 ? (targetRow.Cells[13].Value?.ToString() ?? "") : "";
    EmailTb.Text = targetRow.Cells.Count > 14 ? (targetRow.Cells[14].Value?.ToString() ?? "") : "";
    gsmpTb.Text = targetRow.Cells.Count > 9 ? (targetRow.Cells[9].Value?.ToString() ?? "") : "";
    gsmmTb.Text = targetRow.Cells.Count > 12 ? (targetRow.Cells[12].Value?.ToString() ?? "") : "";
    gsmTb.Text = targetRow.Cells.Count > 5 ? (targetRow.Cells[5].Value?.ToString() ?? "") : "";
}

2. 验证列索引的有效性

检查你的DataGridView实际列数是否支持你使用的索引(比如Cells[14]要求至少有15列)。可以通过以下方式确认:

  • 在设计器中查看DataGridView的列数
  • 加入调试代码输出当前列数:
// 在事件开头加入调试代码
Console.WriteLine($"当前DataGridView列数:{MemberSDGV.Columns.Count}");

如果列数不足,需要调整数据源或列索引,确保所有使用的索引都小于Columns.Count。

3. 可选:优化行选中行为

如果希望点击单元格时自动选中整行,可以在设计器或代码中设置:

MemberSDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

这能让SelectedRows集合更稳定,但即使设置了这个,仍建议保留索引有效性判断,避免极端场景报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:35:13