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

如何对比DataGridView中选中行的Description列单元格值?

解决方案

核心逻辑梳理

  1. 筛选出所有复选框被选中的有效行(排除DataGridView默认的新行)
  2. 当选中行数≥2时,提取这些行的Description列值
  3. 检查所有值是否一致:
    • 若不一致:弹出提示框
    • 若一致:将该值填入目标文本框

完整代码实现

推荐使用CellValueChanged事件替代CellClick,因为复选框状态变更会直接触发该事件,逻辑更精准:

private void datagridview1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // 仅处理复选框列的变更
    if (e.ColumnIndex == 0 && e.RowIndex >= 0)
    {
        // 收集所有选中的有效行(排除新行)
        var selectedRows = datagridview1.Rows.Cast<DataGridViewRow>()
            .Where(r => !r.IsNewRow && Convert.ToBoolean(r.Cells[0].Value))
            .ToList();

        // 仅当选中行数≥2时执行对比逻辑
        if (selectedRows.Count >= 2)
        {
            // 获取第一行的Description值作为基准
            string baseValue = selectedRows[0].Cells["Description"].Value?.ToString();
            bool allSame = true;

            // 遍历剩余选中行对比值
            foreach (var row in selectedRows.Skip(1))
            {
                string currentValue = row.Cells["Description"].Value?.ToString();
                if (currentValue != baseValue)
                {
                    allSame = false;
                    break;
                }
            }

            // 根据对比结果执行操作
            if (!allSame)
            {
                MessageBox.Show("选中行的Description值不一致!");
            }
            else
            {
                // 假设你的文本框名为txtDescription
                txtDescription.Text = baseValue;
            }
        }
        else if (selectedRows.Count == 1)
        {
            // 可选:选中单行时的操作,比如填入对应值
            txtDescription.Text = selectedRows[0].Cells["Description"].Value?.ToString();
        }
        else
        {
            // 没有选中行时清空文本框
            txtDescription.Text = string.Empty;
        }
    }
}

关键说明

  • 排除新行:通过!r.IsNewRow过滤DataGridView自动生成的空行,避免无效数据干扰
  • 基准对比法:拿第一行的Description值作为基准,和其他行逐一对比,效率更高
  • 事件选择:CellValueChanged比CellClick更可靠,因为点击复选框的空白区域不会误触发逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:01:34