Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# datagridview合并单元格

作者:夏威夷丶霪男   发布日期:2025-12-30   浏览:81

using System;
using System.Windows.Forms;

public class DataGridViewMergeCells : Form
{
    private DataGridView dataGridView1;

    public DataGridViewMergeCells()
    {
        dataGridView1 = new DataGridView();
        dataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(dataGridView1);

        // 添加一些示例数据
        dataGridView1.Rows.Add("A", "B", "C");
        dataGridView1.Rows.Add("A", "B", "D");
        dataGridView1.Rows.Add("E", "F", "G");

        // 合并相同的单元格
        MergeCells(dataGridView1);
    }

    private void MergeCells(DataGridView dgv)
    {
        for (int col = 0; col < dgv.Columns.Count; col++)
        {
            int currentRow = 0;
            while (currentRow < dgv.Rows.Count - 1)
            {
                int mergeCount = 1;
                while (currentRow + mergeCount < dgv.Rows.Count &&
                       dgv.Rows[currentRow].Cells[col].Value?.ToString() == 
                       dgv.Rows[currentRow + mergeCount].Cells[col].Value?.ToString())
                {
                    mergeCount++;
                }

                if (mergeCount > 1)
                {
                    dgv.Rows[currentRow].Cells[col].Style.WrapMode = DataGridViewTriState.True;
                    dgv.Rows[currentRow].Height = dgv.Rows[currentRow].Height * mergeCount;
                    for (int i = 1; i < mergeCount; i++)
                    {
                        dgv.Rows[currentRow + i].Cells[col].Visible = false;
                    }
                }

                currentRow += mergeCount;
            }
        }
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new DataGridViewMergeCells());
    }
}

解释说明:

  1. DataGridView控件:创建了一个DataGridView控件,并添加了一些示例数据。
  2. 合并单元格逻辑:通过遍历每一列,检查相邻行的值是否相同。如果相同,则将这些单元格合并。
  3. 合并方式:通过设置第一个单元格的高度,并隐藏后续重复的单元格来实现视觉上的合并效果。

请注意,这段代码只是一个简单的示例,实际应用中可能需要根据具体需求进行调整和优化。

上一篇:c# 替换字符串

下一篇:c# https

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站