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

DataGridView仅含1行时触发ArgumentOutOfRangeException问题求助

解决非绑定DataGridView移动行时剩余1行触发ArgumentOutOfRangeException的问题

我之前做类似功能的时候也踩过这个坑,这个异常大概率是操作行时没处理好选中状态或索引的边界情况,尤其是当DataGridView只剩最后一行的时候。下面给你分析原因和具体的解决办法:

常见触发原因

  • 当DataGridView只剩1行,移除它之后,代码还尝试访问SelectedRows[0],但此时SelectedRows.Count已经是0,直接索引访问就会抛出越界异常。
  • 非绑定模式下直接操作Rows集合,移除行后控件的选中状态没有同步更新,导致后续操作(比如误判选中行存在)出错。
  • 移除行的顺序有问题:比如先移除行再获取选中行的引用,这时候引用已经失效。

修复后的代码示例

Add按钮(左→右移动行)

private void btnAdd_Click(object sender, EventArgs e)
{
    // 先校验:左侧无选中行直接返回
    if (dataGridViewLeft.SelectedRows.Count == 0)
        return;

    // 先克隆选中行并复制单元格值(Clone方法不会复制单元格内容)
    DataGridViewRow targetRow = dataGridViewLeft.SelectedRows[0].Clone() as DataGridViewRow;
    foreach (DataGridViewCell cell in dataGridViewLeft.SelectedRows[0].Cells)
    {
        targetRow.Cells[cell.ColumnIndex].Value = cell.Value;
    }

    // 先添加到右侧,再从左侧移除(避免移除后选中行引用失效)
    dataGridViewRight.Rows.Add(targetRow);
    dataGridViewLeft.Rows.Remove(dataGridViewLeft.SelectedRows[0]);

    // 关键:左侧无行时清除选中状态,防止后续误操作
    if (dataGridViewLeft.Rows.Count == 0)
    {
        dataGridViewLeft.ClearSelection();
    }
}

Delete按钮(右→左移动行)

private void btnDelete_Click(object sender, EventArgs e)
{
    if (dataGridViewRight.SelectedRows.Count == 0)
        return;

    DataGridViewRow targetRow = dataGridViewRight.SelectedRows[0].Clone() as DataGridViewRow;
    foreach (DataGridViewCell cell in dataGridViewRight.SelectedRows[0].Cells)
    {
        targetRow.Cells[cell.ColumnIndex].Value = cell.Value;
    }

    dataGridViewLeft.Rows.Add(targetRow);
    dataGridViewRight.Rows.Remove(dataGridViewRight.SelectedRows[0]);

    if (dataGridViewRight.Rows.Count == 0)
    {
        dataGridViewRight.ClearSelection();
    }
}

额外优化建议

如果你的数据量不小,更推荐用绑定数据源的方式来实现:

  1. 为左右两个DataGridView分别创建对应的集合(比如List<YourDataModel> leftDataList和rightDataList)。
  2. 将集合绑定到DataGridView的DataSource属性。
  3. 移动行时直接操作集合,然后刷新绑定(比如dataGridViewLeft.DataSource = null; dataGridViewLeft.DataSource = leftDataList;)。
    这种方式能避免直接操作Rows集合带来的索引混乱,代码也更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:08:06