惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
Vulnerabilities – Threatpost
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
C
CXSECURITY Database RSS Feed - CXSecurity.com
P
Privacy International News Feed
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
MyScale Blog
MyScale Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
L
LINUX DO - 最新话题
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Cloudflare Blog
美团技术团队
Recorded Future
Recorded Future
T
Tailwind CSS Blog
Latest news
Latest news
Security Archives - TechRepublic
Security Archives - TechRepublic
Security Latest
Security Latest
Know Your Adversary
Know Your Adversary
Cloudbric
Cloudbric
Schneier on Security
Schneier on Security
I
Intezer
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
云风的 BLOG
云风的 BLOG
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
L
LangChain Blog
爱范儿
爱范儿
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
W
WeLiveSecurity
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
SecWiki News
SecWiki News
V2EX - 技术
V2EX - 技术
IT之家
IT之家
Cyberwarzone
Cyberwarzone
F
Full Disclosure
Spread Privacy
Spread Privacy
阮一峰的网络日志
阮一峰的网络日志

博客园 - soulsjie

一种在winfrom窗体中显示计算公式的解决方案 C#GDI+阴影笔刷样式HatchStyle探讨 C#代码混淆工具ConfuserEx的使用 Aspose.Words在指定位置插入图片、调整图片大小 C#获取对象实体的键值对信息 C#将Winform上的TextBox和ComBox的值导入和导出 C#使用Aspose.Words将Spread表格插入到Word中 C# Aspose.Words将word中自定义的标签进行替换 Python文件操作基础方法 C# 将项目资源文件保存到磁盘上 SqlSugar数据库辅助类 使用存储过程备份MS SQLServer数据库 案例3:JAVA GUI 随机点名程序 案例2:JAVA GUI 简易计算器 ArcGIS JS API 添加要素图层 点击时获取图层属性 ArcGIS JS API 将天地图设置为底图 HTML5PLUS实现类似右侧弹出菜单 SqlSugar各数据库连接串 案例1:JAVAGUI用户管理
winform窗体DataGridView合并单元格处理
soulsjie · 2024-07-10 · via 博客园 - soulsjie

文本是使用SunnyUI的UIDataGridView控件进行演示的,同样适用于System.Windows.Forms.DataGridView控件

具体需求如下,下表是个成绩表,其中姓名、总分、平均分这三列信息重复,需要对数据表进行合并单元格处理。

 实现该需求需要两个步骤:

1.给表格添加单元格重绘事件

 在方法uiDataGridView1_CellPainting中添加代码将需要合并的列的单元格边框去掉

if (e.RowIndex >= 0 && (e.ColumnIndex == 0 || e.ColumnIndex == 3 || e.ColumnIndex == 4))
            {
                // 不显示单元格边框
                e.AdvancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None;
            }

使用MergeCells方法,将指定单元格合并,原理是把要合并的单元格的内容清掉,然后在合并的中间行位置再将数值打出,实现合并的效果。

public void MergeCells(DataGridView dataGridView, int startRow, int endRow, int column, Color color)
        {
            if (dataGridView.Columns.Count <= column || startRow < 0 || endRow >= dataGridView.Rows.Count || startRow >= endRow)
            {
                return;
            }

            DataGridViewCell cell = dataGridView[column, startRow];
            string cellValue = cell.Value != null ? cell.Value.ToString() : "";

            for (int i = startRow; i <= endRow; i++)
            {
                dataGridView[column, i].Value = null;
            }
            //在中间的行写值
            int valRowIndex = 0;
            int rows = endRow - startRow + 1;
            int halfRow = rows / 2;
            valRowIndex = startRow + halfRow;

            DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();
            textBoxCell.Value = cellValue;
            dataGridView[column, valRowIndex] = textBoxCell;


            for (int i = startRow; i <= endRow; i++)
            {
                dataGridView[column, i].Style.BackColor = color;
                dataGridView[column, i].ReadOnly = true; // 设置合并后的单元格只读
                dataGridView[column, i].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; // 设置文本居中
                dataGridView[column, i].Style.Padding = new Padding(0); // 设置内边距为0,达到不显示边框的效果
                dataGridView[column, i].Style.SelectionBackColor = dataGridView[column, i].Style.BackColor; // 设置选中背景色与背景色一致
            }
        }

调用:

            //合并 张三
            MergeCells(uiDataGridView1, 0, 2, 0, Color.Pink);
            MergeCells(uiDataGridView1, 0, 2, 3, Color.Pink);
            MergeCells(uiDataGridView1, 0, 2, 4, Color.Pink);
            //合并 李四
            MergeCells(uiDataGridView1, 3, 5, 0, Color.Gray);
            MergeCells(uiDataGridView1, 3, 5, 3, Color.Gray);
            MergeCells(uiDataGridView1, 3, 5, 4, Color.Gray);

最终效果如下:

整个Form1.cs如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyForm
{
    public partial class Form1 : Form
    {
        private Random random = new Random();

        public Form1()
        {
            InitializeComponent();
            LoadData();
            //合并 张三
            MergeCells(uiDataGridView1, 0, 2, 0, Color.Pink);
            MergeCells(uiDataGridView1, 0, 2, 3, Color.Pink);
            MergeCells(uiDataGridView1, 0, 2, 4, Color.Pink);
            //合并 李四
            MergeCells(uiDataGridView1, 3, 5, 0, Color.Gray);
            MergeCells(uiDataGridView1, 3, 5, 3, Color.Gray);
            MergeCells(uiDataGridView1, 3, 5, 4, Color.Gray);
        }

        void LoadData()
        {
            List<Score> scores = new List<Score>();
            scores.Add(new Score() { Name = "张三", Subject = "数学", Mark = 68, Sum = 0, Avg = 0 });
            scores.Add(new Score() { Name = "张三", Subject = "语文", Mark = 100, Sum = 0, Avg = 0 });
            scores.Add(new Score() { Name = "张三", Subject = "英语", Mark = 35, Sum = 0, Avg = 0 });
            scores.Add(new Score() { Name = "李四", Subject = "数学", Mark = 26, Sum = 0, Avg = 0 });
            scores.Add(new Score() { Name = "李四", Subject = "语文", Mark = 85, Sum = 0, Avg = 0 });
            scores.Add(new Score() { Name = "李四", Subject = "英语", Mark = 48, Sum = 0, Avg = 0 });
            uiDataGridView1.RowCount = scores.Count();
            for (int i = 0; i < scores.Count(); i++)
            {
                uiDataGridView1.Rows[i].Cells[0].Value = scores[i].Name;
                uiDataGridView1.Rows[i].Cells[1].Value = scores[i].Subject;
                uiDataGridView1.Rows[i].Cells[2].Value = scores[i].Mark;
                uiDataGridView1.Rows[i].Cells[3].Value = scores.Where(o=>o.Name== scores[i].Name).Select(o => o.Mark).Sum();
                uiDataGridView1.Rows[i].Cells[4].Value = Math.Round(scores.Where(o => o.Name == scores[i].Name).Select(o => o.Mark).Average(), 2);
            }
        }

        public void MergeCells(DataGridView dataGridView, int startRow, int endRow, int column, Color color)
        {
            if (dataGridView.Columns.Count <= column || startRow < 0 || endRow >= dataGridView.Rows.Count || startRow >= endRow)
            {
                return;
            }

            DataGridViewCell cell = dataGridView[column, startRow];
            string cellValue = cell.Value != null ? cell.Value.ToString() : "";

            for (int i = startRow; i <= endRow; i++)
            {
                dataGridView[column, i].Value = null;
            }
            //在中间的行写值
            int valRowIndex = 0;
            int rows = endRow - startRow + 1;
            int halfRow = rows / 2;
            valRowIndex = startRow + halfRow;

            DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();
            textBoxCell.Value = cellValue;
            dataGridView[column, valRowIndex] = textBoxCell;


            for (int i = startRow; i <= endRow; i++)
            {
                dataGridView[column, i].Style.BackColor = color;
                dataGridView[column, i].ReadOnly = true; // 设置合并后的单元格只读
                dataGridView[column, i].Style.Alignment = DataGridViewContentAlignment.MiddleCenter; // 设置文本居中
                dataGridView[column, i].Style.Padding = new Padding(0); // 设置内边距为0,达到不显示边框的效果
                dataGridView[column, i].Style.SelectionBackColor = dataGridView[column, i].Style.BackColor; // 设置选中背景色与背景色一致
            }
        }

        private void uiDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && (e.ColumnIndex == 0 || e.ColumnIndex == 3 || e.ColumnIndex == 4))
            {
                // 不显示单元格边框
                e.AdvancedBorderStyle.All = DataGridViewAdvancedCellBorderStyle.None;
            }
        }
    }


    public class Score
    {
        public string Name { get; set; }

        public string Subject { get; set; }

        public double Mark { get; set; }

        public double Sum { get; set; }

        public double Avg { get; set; }
    }

}