借鉴别人的,改了改,没用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 实现二维表头和行合并的更多相关文章

  1. Datagridview 实现二维表头和行合并【转载】

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; u ...

  2. 如何通过DataGridView 实现单元格合并和二维表头

    先看下实现出来的效果(这里随便写了几组数据,用来测试) 先初始一个DataGridView 设置哪几列 DataGridView 里男女这两列的 AutoSizeMode 可以设置Fill. publ ...

  3. 【Winform-自定义控件】DataGridView 单元格合并和二维表头

    DataGridView单元格合并和二维表头应用: //DataGridView绑定数据 DataTable dt = new DataTable(); dt.Columns.Add("); ...

  4. PyTorch 如何理解张量:一维张量、二维张量、行/列向量、矩阵

    理解张量,并将张量与线性代数的知识连接起来,我认为最重要的是理解 tensor 的两个属性:shape 和 ndim . ndim 表示张量的维度,一维张量的 ndim 值为 1,二维张量的 ndim ...

  5. C#获取二维数组的行数和列数及其多维。。。

    原文发布时间为:2008-11-26 -- 来源于本人的百度文章 [由搬家工具导入] 有一个二维数组sz[,] 怎样获取sz 的行数和列数呢? sz.GetLength(0) 返回第一维的长度(即行数 ...

  6. (转)DataGridView多维表头及其扩展功能

    dataGridView1.RowHeadersVisible = false;把整行选中那一列去掉.如果需要整行选中,新增一按钮列模拟实现.上源码:多维DataGridView 有个简易的方法: 1 ...

  7. C#中如何获取一个二维数组的两维长度,即行数和列数?以及多维数组各个维度的长度?

    如何获取二维数组中的元素个数呢? int[,] array = new int[,] {{1,2,3},{4,5,6},{7,8,9}};//定义一个3行3列的二维数组int row = array. ...

  8. C#中Winform程序中如何实现多维表头【不通过第三方报表程序】

    问题:C#中Winform程序中如何实现多维表头. 在网上搜了很多方法,大多数方法对于我这种新手,看的都不是很懂.最后在新浪博客看到了一篇比较易懂的文章:[DataGridView二维表头与合并单元格 ...

  9. 扫二维码下载apk并统计被扫描次数(及微信屏蔽下载解决方案)

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/5395715.html 需求:想让用户扫描一个二维码就能下载APP,并统计被扫描次数. 两种实现方法: 1.一 ...

随机推荐

  1. Qt creator中配置opencv win7 64bit

    配置方法的原文来自https://www.librehat.com/qt-5-2-vs2012-opencv-2-4-7-dev-environment-setup-tutorial/. 补充,在张静 ...

  2. Ubuntu13.04闪屏的问题

    我的电脑Y460,双显切换,win7+ubuntu双系统,就是这个坑爹的双显切换,导致安装ubuntu13.04后屏老闪,网上查阅资料得知是显卡问题,一种是说显卡驱动问题,一种是说双显卡问题,双显卡问 ...

  3. Navicat Premium 12安装和破解

    链接:https://pan.baidu.com/s/1x8AFWlJYGIl3TlbA1vX63g 提取码:9hu0  安装步骤: 1.下载好后点击navicat12018_premium_cs_x ...

  4. Java 接口理解

    学习Spring有一段时间了,对java也有了一点了解,最不能理解的就是接口, 即使是写了接口并实现了它,依然无法理解它到底有什么用?看了其他几篇博客,总结了一下自己的理解. 在JAVA编程语言中是一 ...

  5. matlab 高级

    绘图 条形图 x = [1:10]; y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95]; bar(x,y), xlabel('Student'),ylabel( ...

  6. 基于libcurl的POST(http)

    #include <stdio.h> #include <curl/curl.h> int main (void) { char *url="http://www.n ...

  7. vue每次运行起来端口不一致问题

    原因:portfinder新发布的版本异常 解决方案:npm install portfinder@1.0.21

  8. F5负载均衡综合实例详解(转)

    转载自:https://blog.csdn.net/weixin_43089453/article/details/87937994  女程序员就不脱发了吗来源于:<网络运维与管理>201 ...

  9. 吴裕雄--天生自然 JAVA开发学习:方法

    /** 返回两个整型变量数据的较大值 */ public static int max(int num1, int num2) { int result; if (num1 > num2) re ...

  10. python学习笔记--数据类型和变量总结

    1.数据类型 字符串 数字 列表 元祖 字典 2.可变不可变划分 可变:列表,字典 不可变:字符串,数字,元祖 举例:字符串,通过id查看字符串变量在内存中的地址.两次存的值不一样,这就说明了内存重新 ...