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

C# 将Datagridview选中行添加到Client类列表集合问题

修复方案

核心错误点

  • 索引越界:DataGridView行索引范围为0 至 ClientsGrid.RowCount - 1,原代码循环初始值设为ClientsGrid.RowCount,访问Rows[i]会直接触发索引超出范围异常。
  • 行匹配错误:判断选中状态使用Rows[i-1],取数时使用Rows[i],判断和取值的不是同一行,数据完全不匹配。
  • 构造参数缺失:Client类构造函数要求传入10个参数,原代码仅传入9个参数,编译无法通过。
  • 空值未处理:单元格值为null时直接调用ToString()会触发空引用异常。

修正后代码

选中行添加到列表逻辑

List<Client> Listclient = new List<Client>();
// 倒序遍历所有有效行
for (int i = ClientsGrid.RowCount - 1; i >= 0; i--)
{
    // 校验首列选中状态,判断和取数使用同一行索引
    if (ClientsGrid.Rows[i].Cells[0].Value != null 
        && (bool)ClientsGrid.Rows[i].Cells[0].Value)
    {
        // 空值安全处理所有字段
        string col1 = ClientsGrid.Rows[i].Cells[1].Value?.ToString() ?? string.Empty;
        string col2 = ClientsGrid.Rows[i].Cells[2].Value?.ToString() ?? string.Empty;
        string col3 = ClientsGrid.Rows[i].Cells[3].Value?.ToString() ?? string.Empty;
        string col4 = ClientsGrid.Rows[i].Cells[4].Value?.ToString() ?? string.Empty;
        string col5 = ClientsGrid.Rows[i].Cells[5].Value?.ToString() ?? string.Empty;
        string col6 = ClientsGrid.Rows[i].Cells[6].Value?.ToString() ?? string.Empty;
        string col7 = ClientsGrid.Rows[i].Cells[7].Value?.ToString() ?? string.Empty;
        string col8 = ClientsGrid.Rows[i].Cells[8].Value?.ToString() ?? string.Empty;
        string col9 = ClientsGrid.Rows[i].Cells[9].Value?.ToString() ?? string.Empty;
        // 补充缺失的第10个参数,根据实际DGV列顺序调整索引即可
        string col10 = ClientsGrid.Rows[i].Cells[10].Value?.ToString() ?? string.Empty;
        
        Listclient.Add(new Client(col1, col2, col3, col4, col5, col6, col7, col8, col9, col10));
    }
}

验证代码无需修改,只要参数顺序和Client构造函数要求一致,即可正常打印客户姓氏。

内容的提问来源于stack exchange,提问作者aymen.gassa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:54:01