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

如何将DataGridView中高亮行的数据传递至另一个DataGridView?

解决DataGridView红色背景行数据传递问题

原代码的问题出在这几个地方:

  • 把列索引当成了行索引用:idx是列"A"的索引,却用来定位dataGridView2的行,逻辑完全错误
  • 重复判断行背景色:在每个单元格循环里反复检查行的背景色,纯属多余
  • 没处理目标表格的行创建:如果dataGridView2没有足够的行,直接赋值会触发索引越界错误

修正后的代码(列结构一致时用)

如果dataGridView2的列和dataGridView1完全对应,用这段代码最直接:

private void Button1_Click(object sender, EventArgs e)
{
    // 先清空目标表格的现有行,避免重复数据
    dataGridView2.Rows.Clear();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // 跳过自动生成的空新行(如果允许添加新行的话)
        if (row.IsNewRow) continue;

        // 检查当前行背景色是否为红色
        if (row.DefaultCellStyle.BackColor == Color.Red)
        {
            // 复制当前行的所有单元格值
            object[] rowData = new object[row.Cells.Count];
            for (int i = 0; i < row.Cells.Count; i++)
            {
                rowData[i] = row.Cells[i].Value;
            }
            // 把复制好的数据添加到目标表格
            dataGridView2.Rows.Add(rowData);
        }
    }
}

只传递特定列的情况

如果只需要传递指定列(比如只传列"A"和列"B"),可以用这段:

private void Button1_Click(object sender, EventArgs e)
{
    dataGridView2.Rows.Clear();

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow) continue;

        if (row.DefaultCellStyle.BackColor == Color.Red)
        {
            // 获取要传递的列索引
            int colAIdx = dataGridView1.Columns["A"].Index;
            int colBIdx = dataGridView1.Columns["B"].Index;

            // 构造要添加的行数据
            object[] rowData = new object[]
            {
                row.Cells[colAIdx].Value,
                row.Cells[colBIdx].Value
                // 需要其他列的话继续往后加
            };
            dataGridView2.Rows.Add(rowData);
        }
    }
}

关键调整说明

  • 先清空目标行:避免重复添加数据,保持表格整洁
  • 跳过新行:默认DataGridView会有一行空的新行,跳过它防止无效数据
  • 先判断行背景色再处理整行:减少冗余判断,提升效率
  • 用Rows.Add()添加新行:自动创建对应行,不会出现索引越界的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:52:44