Datagridview 实现二维表头和行合并
借鉴别人的,改了改,没用timer

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Design;
namespace Salem.Library.Control.DataGridView
{
/// <summary>
/// 拥有默认样式带合并表头功能的DataGridView
/// </summary>
public partial class DataGridViewEx : System.Windows.Forms.DataGridView
{
#region 字段属性
//是否显示行号
private bool showNum = false;
/// <summary>
/// 是否显示行号
/// </summary>
[DefaultValue(true), Description("是否显示行号")]
public bool ShowNum
{
get
{
return showNum;
}
set
{
showNum = value;
if (value)
{
this.RowHeadersVisible = true;
}
}
}
private Dictionary<int, SpanInfo> SpanRows = new Dictionary<int, SpanInfo>();
private List<string> _mergecolumnname = new List<string>();
/// <summary>
/// 合并列的名称
/// </summary>
[MergableProperty(false), Editor("System.Windows.Forms.Design.ListControlStringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor)), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), Localizable(true), Description("设置或获取合并列的集合"), Browsable(true), Category("单元格合并")]
public List<string> MergeColumnNames
{
get
{
return this._mergecolumnname;
}
set
{
this._mergecolumnname = value;
}
}
#endregion
#region 构造函数
public DataGridViewEx()
{
SetProperty();
SetStyle(
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw |
ControlStyles.DoubleBuffer, true);
InitializeComponent();
}
#endregion
#region 样式设置方法
//设置样式属性
private void SetProperty()
{
this.AutoGenerateColumns = false;
this.BackgroundColor = Color.White;
//设置奇数行单元格的样式
this.AlternatingRowsDefaultCellStyle = CreatAlternatingCellStyle();
//设置默认单元格的样式
this.DefaultCellStyle = CreatDefaultCellStyle();
this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(247, 247, 247);
this.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 10);
//this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.CellBorderStyle = DataGridViewCellBorderStyle.SunkenHorizontal;
this.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
this.ColumnHeadersHeight = 35;
this.EnableHeadersVisualStyles = false;
this.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
this.RowHeadersVisible = false;
this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.RowTemplate.Height = 35;
}
//设置奇数行的样式
private DataGridViewCellStyle CreatAlternatingCellStyle()
{
DataGridViewCellStyle alternatingRowStyle = new DataGridViewCellStyle();
alternatingRowStyle.Font = new System.Drawing.Font("宋体", 10);
//alternatingRowStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
alternatingRowStyle.BackColor = Color.White;
alternatingRowStyle.ForeColor = Color.Black;
alternatingRowStyle.SelectionBackColor = Color.FromArgb(255, 230, 162);
alternatingRowStyle.SelectionForeColor = Color.Black;
return alternatingRowStyle;
}
//设置默认单元格的样式
private DataGridViewCellStyle CreatDefaultCellStyle()
{
DataGridViewCellStyle defaultCellStyle = new DataGridViewCellStyle();
//defaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
defaultCellStyle.Font = new System.Drawing.Font("宋体", 10);
defaultCellStyle.BackColor = Color.White;
defaultCellStyle.ForeColor = Color.Black;
defaultCellStyle.SelectionBackColor = Color.FromArgb(255, 230, 162);
defaultCellStyle.SelectionForeColor = Color.Black;
return defaultCellStyle;
}
/// <summary>
/// 设置单元格和列头有边框
/// </summary>
public void SetGirdCellAndColHeaderBorderStyle()
{
this.CellBorderStyle = DataGridViewCellBorderStyle.Single;
this.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
}
#endregion
#region 重绘方法
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
try
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
//DrawCell(e);
}
else
{
//合并表头
if (e.RowIndex == -1)
{
if (SpanRows.ContainsKey(e.ColumnIndex)) //被合并的列
{
//画边框
Graphics g = e.Graphics;
e.Paint(e.CellBounds, DataGridViewPaintParts.Background | DataGridViewPaintParts.Border);
int left = e.CellBounds.Left, top = e.CellBounds.Top + 2,
right = e.CellBounds.Right, bottom = e.CellBounds.Bottom;
switch (SpanRows[e.ColumnIndex].Position)
{
case 1:
left += 2;
break;
case 2:
break;
case 3:
right -= 2;
break;
}
//画底色
g.FillRectangle(new SolidBrush(e.CellStyle.BackColor), left, top,
right - left, (bottom - top)/2);
//画中线
g.DrawLine(new Pen(this.GridColor), left-2, (top + bottom) / 2,
right, (top + bottom) / 2);
//写合并标题
StringFormat _sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
g.DrawString(e.Value + "", e.CellStyle.Font, Brushes.Black,
new Rectangle(left, (top + bottom) / 2, right - left, (bottom - top) / 2), _sf);
//写原来列标题
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
left = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Left, true).Left - 2;
if (left < 0) left = this.GetCellDisplayRectangle(-1, -1, true).Width;
right = this.GetColumnDisplayRectangle(SpanRows[e.ColumnIndex].Right, true).Right - 2;
if (right < 0) right = this.Width;
g.DrawString(SpanRows[e.ColumnIndex].Text, this.ColumnHeadersDefaultCellStyle.Font, new SolidBrush(e.CellStyle.ForeColor),
new Rectangle(left, top, right - left, (bottom - top)/2), sf);
e.Handled = true;
}
}
}
base.OnCellPainting(e);
}
catch
{ }
}
//绘制行号
protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)
{
if (ShowNum)
{
this.RowHeadersVisible = true;
SolidBrush solidBrush = new SolidBrush(Color.Black);
e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, solidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5);
}
base.OnRowPostPaint(e);
}
//重绘滚动条
protected override void OnScroll(ScrollEventArgs e)
{
this.ReDrawHead();
base.OnScroll(e);
}
//重绘标题行
public void ReDrawHead()
{
foreach (int num in this.SpanRows.Keys)
{
base.Invalidate(base.GetCellDisplayRectangle(num, -1, true));
}
}
#endregion
#region 自定义方法
/// <summary>
/// 画单元格
/// </summary>
/// <param name="e"></param>
private void DrawCell(DataGridViewCellPaintingEventArgs e)
{
if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
{
e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
Brush gridBrush = new SolidBrush(this.GridColor);
SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int cellwidth;
//上面相同的行数
int UpRows = 0;
//下面相同的行数
int DownRows = 0;
//总行数
int count = 0;
if (this.MergeColumnNames.Contains(this.Columns[e.ColumnIndex].Name) && e.RowIndex != -1)
{
cellwidth = e.CellBounds.Width;
Pen gridLinePen = new Pen(gridBrush);
string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();
if (!string.IsNullOrEmpty(curValue))
{
#region 获取下面的行数
for (int i = e.RowIndex; i < this.Rows.Count; i++)
{
if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
{
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
if (!this.Rows[i].Cells[0].Value.ToString().Equals(this.Rows[e.RowIndex].Cells[0].Value.ToString()))
break;
DownRows++;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
#endregion
#region 获取上面的行数
for (int i = e.RowIndex; i >= 0; i--)
{
if (this.Rows[i].Cells[e.ColumnIndex].Value.ToString().Equals(curValue))
{
if (!this.Rows[e.RowIndex].Cells[0].Value.ToString().Equals(this.Rows[i].Cells[0].Value.ToString()))
{
break;
}
//this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
UpRows++;
if (e.RowIndex != i)
{
cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
}
}
else
{
break;
}
}
#endregion
count = DownRows + UpRows - 1;
if (count < 2)
{
return;
}
}
if (this.Rows[e.RowIndex].Selected)
{
backBrush.Color = e.CellStyle.SelectionBackColor;
fontBrush.Color = e.CellStyle.SelectionForeColor;
}
//以背景色填充
e.Graphics.FillRectangle(backBrush, e.CellBounds);
//画字符串
PaintingFont(e, cellwidth, UpRows, DownRows, count);
if (DownRows == 1)
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
count = 0;
}
// 画右边线
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
e.Handled = true;
}
}
/// <summary>
/// 画字符串
/// </summary>
/// <param name="e"></param>
/// <param name="cellwidth"></param>
/// <param name="UpRows"></param>
/// <param name="DownRows"></param>
/// <param name="count"></param>
private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
{
SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
int cellheight = e.CellBounds.Height;
if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
}
else
{
e.Graphics.DrawString((String)e.Value, e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
}
}
#endregion
#region 合并表头方法
/// <summary>
/// 合并列
/// </summary>
/// <param name="ColIndex">列的索引</param>
/// <param name="ColCount">需要合并的列数</param>
/// <param name="Text">合并列后的文本</param>
public void AddSpanHeader(int ColIndex, int ColCount, string Text)
{
if (ColCount < 2)
{
//throw new Exception("行宽应大于等于2,合并1列无意义。");
}
//将这些列加入列表
int Right = ColIndex + ColCount - 1; //同一大标题下的最后一列的索引
SpanRows[ColIndex] = new SpanInfo(Text, 1, ColIndex, Right); //添加标题下的最左列
SpanRows[Right] = new SpanInfo(Text, 3, ColIndex, Right); //添加该标题下的最右列
for (int i = ColIndex + 1; i < Right; i++) //中间的列
{
SpanRows[i] = new SpanInfo(Text, 2, ColIndex, Right);
}
}
/// <summary>
/// 清除合并表头
/// </summary>
public void ClearSpanInfo()
{
this.SpanRows.Clear();
}
#endregion
#region 获取绑定数据
/// <summary>
/// 获取显示列绑定数据
/// </summary>
/// <returns></returns>
public DataTable GetVisibleBoundData()
{
DataTable dt = new DataTable();
foreach (DataGridViewColumn dgvc in this.Columns)
{
if (!dgvc.Visible || string.IsNullOrEmpty(dgvc.HeaderText))
{
continue;
}
if (dgvc is DataGridViewTextBoxColumn || dgvc is DataGridViewComboBoxColumn || dgvc is DataGridViewLinkColumn)
{
if (!dt.Columns.Contains(dgvc.HeaderText) && dgvc.HeaderText.Length > 0)
{
if (dgvc.ValueType == null)
{
dt.Columns.Add(dgvc.HeaderText);
}
else
{
dt.Columns.Add(dgvc.HeaderText, dgvc.ValueType);
}
}
}
}
foreach (DataGridViewRow dgvr in this.Rows)
{
if (dgvr.IsNewRow)
{
continue;
}
if (string.IsNullOrEmpty(dgvr.Cells[1].Value != null ? dgvr.Cells[1].Value.ToString() : ""))
{
continue;
}
DataRow dr = dt.NewRow();
foreach (DataGridViewColumn dgvc in this.Columns)
{
if (dt.Columns.Contains(dgvc.HeaderText))
{
if (dgvr.Cells[dgvc.Name].FormattedValue.ToString().Length > 0)
{
dr[dgvc.HeaderText] = dgvr.Cells[dgvc.Name].FormattedValue;
}
}
}
dt.Rows.Add(dr);
}
return dt;
}
#endregion
}
[StructLayout(LayoutKind.Sequential)]
public struct SpanInfo
{
/// <summary>
/// 合并后的标题
/// </summary>
public string Text;
/// <summary>
/// 本身位置(是左边界列还是有边界列)
/// </summary>
public int Position;
/// <summary>
/// 左边界列
/// </summary>
public int Left;
/// <summary>
/// 右边界列
/// </summary>
public int Right;
public SpanInfo(string Text, int Position, int Left, int Right)
{
this.Text = Text;
this.Position = Position;
this.Left = Left;
this.Right = Right;
}
}
}
使用:
DataTable dt = new DataTable();
dt.Columns.Add("1"); dt.Columns.Add("2"); dt.Columns.Add("3"); dt.Columns.Add("4"); dt.Rows.Add("中国", "上海", "5000", "7000"); dt.Rows.Add("中国", "北京", "3000", "5600"); dt.Rows.Add("美国", "纽约", "6000", "8600"); dt.Rows.Add("美国", "华劢顿", "8000", "9000"); dt.Rows.Add("英国", "伦敦", "7000", "8800"); this.rowMergeView1.DataSource = dt; this.rowMergeView1.ColumnHeadersHeight = 40; this.rowMergeView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; //this.rowMergeView1.MergeColumnNames.Add("Column1"); this.rowMergeView1.AddSpanHeader(2, 2, "XXXX");Datagridview 实现二维表头和行合并的更多相关文章
- Datagridview 实现二维表头和行合并【转载】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; u ...
- 如何通过DataGridView 实现单元格合并和二维表头
先看下实现出来的效果(这里随便写了几组数据,用来测试) 先初始一个DataGridView 设置哪几列 DataGridView 里男女这两列的 AutoSizeMode 可以设置Fill. publ ...
- 【Winform-自定义控件】DataGridView 单元格合并和二维表头
DataGridView单元格合并和二维表头应用: //DataGridView绑定数据 DataTable dt = new DataTable(); dt.Columns.Add("); ...
- PyTorch 如何理解张量:一维张量、二维张量、行/列向量、矩阵
理解张量,并将张量与线性代数的知识连接起来,我认为最重要的是理解 tensor 的两个属性:shape 和 ndim . ndim 表示张量的维度,一维张量的 ndim 值为 1,二维张量的 ndim ...
- C#获取二维数组的行数和列数及其多维。。。
原文发布时间为:2008-11-26 -- 来源于本人的百度文章 [由搬家工具导入] 有一个二维数组sz[,] 怎样获取sz 的行数和列数呢? sz.GetLength(0) 返回第一维的长度(即行数 ...
- (转)DataGridView多维表头及其扩展功能
dataGridView1.RowHeadersVisible = false;把整行选中那一列去掉.如果需要整行选中,新增一按钮列模拟实现.上源码:多维DataGridView 有个简易的方法: 1 ...
- C#中如何获取一个二维数组的两维长度,即行数和列数?以及多维数组各个维度的长度?
如何获取二维数组中的元素个数呢? int[,] array = new int[,] {{1,2,3},{4,5,6},{7,8,9}};//定义一个3行3列的二维数组int row = array. ...
- C#中Winform程序中如何实现多维表头【不通过第三方报表程序】
问题:C#中Winform程序中如何实现多维表头. 在网上搜了很多方法,大多数方法对于我这种新手,看的都不是很懂.最后在新浪博客看到了一篇比较易懂的文章:[DataGridView二维表头与合并单元格 ...
- 扫二维码下载apk并统计被扫描次数(及微信屏蔽下载解决方案)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/5395715.html 需求:想让用户扫描一个二维码就能下载APP,并统计被扫描次数. 两种实现方法: 1.一 ...
随机推荐
- java 微信红包算法代码实现及架构设计
转载至:https://www.zybuluo.com/yulin718/note/93148 微信红包的架构设计简介 架构 @来源于QCon某高可用架构群整理,整理朱玉华. 背景:有某个朋友在朋友圈 ...
- 尝试解决 : Microsoft Visual C++ 14.0 is required 的问题
当在pycharm 中安装 gevent 的时候 发生了 错误 晚上搜索的时候发现 解决问题有两种 方法 1 是 下载 whl 文件 通过二进制的方式 导入模块的包 想了想 ...
- Java多线程之并发包,并发队列
目录 1 并发包 1.1同步容器类 1.1.1Vector与ArrayList区别 1.1.2HasTable与HasMap 1.1.3 synchronizedMap 1.1.4 Concurren ...
- tp5 输入域名即访问指定页面
遇到PC官网类型的项目,经常会遇到隐藏入口文件和输入域名即可打开官网首页的需求.需要修改站点的默认加载文件和伪静态的配置才可以生效. 以下为nginx1.15版本,宝塔面板的修改方式.修改入口文件为w ...
- 2020 年最流行的 Java 开发技术
不知不觉间,2020 年即将于十几天之后到来,作为技术圈中你,准备好迎接最新的变化了吗?在本文中,我们将以编程界最常用的编程语言 Java 为例,分享最为主流的技术与工具. 作者 | divyesh. ...
- Django2.0——模板渲染(一)
在前面的介绍中我们都是用简单的 django.http.HttpResponse来把内容显示到网页上,本节将讲解如何使用渲染模板的方法来显示内容,即调用精美的HTML页面.模板的创建既可以在项目下创建 ...
- CMake命令之export
CMake中与export()相关的命令 (注:红色字体是标题,粉色是需要特别需要注意的地方) 总的来说,export()命令想要做的事情可以用一句话概括:Export targets from th ...
- 88.QuerySet API使用详解:get_or_create和bulk_create方法
get_or_create 根据某个条件进行查找,如果找到了匹配的数据就会返回这条数据,如果没有找到匹配到的数据,就会创建一个.示例代码如下: from django.http import Http ...
- SWIG 3 中文手册——9. SWIG 库
目录 9 SWIG 库 9.1 %include 指令与库搜索路径 9.2 C 数组与指针 9.2.1 cpointer.i 9.2.2 carrays.i 9.2.3 cmalloc.i 9.2.4 ...
- 微服务项目开发学成在线_day02 CMS前端开发
1 Vue.js与Webpack研究 开发版的浏览器:https://www.google.cn/intl/zh-CN/chrome/dev/ 前端的开发框架:微服务项目开发学成在线_Vue.js与W ...