首页 > 其他分享 >winform窗体DataGridView合并单元格处理

winform窗体DataGridView合并单元格处理

时间:2024-07-10 10:57:35浏览次数:10  
标签:Name Color 单元格 System DataGridView 窗体 scores MergeCells uiDataGridView1

文本是使用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; }
    }

}

  

 

标签:Name,Color,单元格,System,DataGridView,窗体,scores,MergeCells,uiDataGridView1
From: https://www.cnblogs.com/soulsjie/p/18293481

相关文章

  • Excel原地跳转单元格
    Excel原地跳转单元格效果:结束编辑状态,并且活动单元格停留在刚才编辑单元格的位置实现:(两种方法)       (1)输入结束后按Ctrl+Enter。       (2)输入结束后点击编辑栏中的√。......
  • (八)ADO.NET用窗体应用程序写增删查改——改(1.1升级版)
    在1.0版本中,紧接前面两节“增”、“删”、“查”代码,这里新增“改”功能一、首先编辑好要修改的控件和相关属性,这里“编号”默认只读属性(ReadOnly)二、其次,修改下窗体显示的代码,让数据直接显示出来,这里我们用一个方法封装好,直接在窗体加载事件(Load)中调用即可。privatevoidFo......
  • C#开发一个混合Windows服务和Windows窗体的程序
    很多时候,我们希望服务程序可以直接运行,或者可以响应一些参数,这时候,混合Windows服务和Windows窗体的程序就排上用场了。要实现同时支持Windows服务和Windows窗体,需要在启动的第一步时判断当前运行环境是否为服务模式,可以从以下几个方面进行判断:会话ID:Process.SessionId,获取当前......
  • C#开发一个混合Windows服务和Windows窗体的程序
    很多时候,我们希望服务程序可以直接运行,或者可以响应一些参数,这时候,混合Windows服务和Windows窗体的程序就排上用场了。要实现同时支持Windows服务和Windows窗体,需要在启动的第一步时判断当前运行环境是否为服务模式,可以从以下几个方面进行判断:当前用户名称:Environment.UserName,......
  • EasyExcel 单元格根据图片数量动态设置宽度
    在使用EasyExcel导出Excel时,如果某个单元格是图片内容,且存在多张图片,此时就需要单元格根据图片数量动态设置宽度。经过自己的研究和实验,导出效果如下:具体代码如下:EasyExcel版本<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactI......
  • 【python小记】使用openpyxl库在同一个工作表下复制单元格(包括它们的值、样式和合并属
    fromopenpyxlimportload_workbook#加载工作簿和工作表wb=load_workbook('test.xlsx')sheet=wb['sheet1']#定义一个函数来复制样式defcopy_style(source_cell,target_cell):ifsource_cell.has_style:target_cell.font=source_cell.font.co......
  • QTableWidget单元格设置控件居中以及背景颜色问题
    QTableWidget的单元格如果要显示其他控件,可以使用setCellWidget,但是控件没有居中,要想使控件居中,可以先创建一个QWidget对象,并设置布局器,然后将控件放到布局器中,并把这个QWidget对象放到单元格内,但是此时若要设置单元格的背景颜色,QTableWidget只能通过设置QTableWidgetItem的颜色来......
  • WPF 分隔栏分割窗体简单测试
    XAML:<Windowx:Class="WpfApp3.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.micro......
  • C#的多线程UI窗体控件显示方案 - 开源研究系列文章
          上次编写了《LUAgent服务器端工具》这个应用,然后里面需要新启动一个线程去对文件进行上传到FTP服务器,但是新线程里无法对应用主线程UI的内容进行更改,所以就需要在线程里设置主UI线程里控件信息的方法,于是就有了此博文。此文记录的是一种高级用法。      为了......
  • Simple WPF: WPF 透明窗体和鼠标事件穿透
    一个自定义WPF窗体的解决方案,借鉴了吕毅老师的WPF制作高性能的透明背景的异形窗口一文,并在此基础上增加了鼠标穿透的功能。可以使得透明窗体的鼠标事件穿透到下层,在下层窗体中响应。这个方法不一定是制作WPF透明窗体最合适的方法,请各路大大不要喷。完整代码地址:Github一、去除......