【Winform-自定义控件】 DataGridView多维表头
[datagridview与treeview绑定]
treeview
代码:
DataTable dtable = new DataTable("Rock");
//添加8列
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
dtable.Columns.Add("", typeof(System.String));
//添加一行数据
DataRow drow = dtable.NewRow();
drow[""] = "";
drow[""] = "";
drow[""] = "";
drow[""] = "";
drow[""] = "";
drow[""] = "";
drow[""] = "";
drow[""] = "";
dtable.Rows.Add(drow);
//绑定数据
multiColHeaderDgv2.DataSource = dtable;
datagridview多维表头实现效果:
自定义控件全部代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel; namespace myMultiColHeaderDgv
{
public class MultiColHeaderDgv:DataGridView
{ #region 字段定義 /// <summary>多維列標題的樹結構
///
/// </summary>
private TreeView _ColHeaderTreeView; /// <summary>樹的最大層數
///
/// </summary>
private int iNodeLevels; /// <summary>一維列標題的高度
///
/// </summary>
private int iCellHeight; /// <summary>所有葉節點
///
/// </summary>
private IList<TreeNode> ColLists = new List<TreeNode>(); #endregion #region 屬性定義 /// <summary>多維列標題的樹結構
///
/// </summary>
[
Description("多維列標題的樹結構")
]
public TreeView myColHeaderTreeView
{
get { return _ColHeaderTreeView; }
set { _ColHeaderTreeView = value; }
} #endregion #region 方法函數 /// <summary>遞歸計算樹最大層數,並保存所有葉節點
///
/// </summary>
/// <param name="tnc"></param>
/// <returns></returns>
private int myGetNodeLevels(TreeNodeCollection tnc)
{
if (tnc == null) return ; foreach (TreeNode tn in tnc)
{
if ((tn.Level + ) > iNodeLevels)//tn.Level是從0開始的
{
iNodeLevels = tn.Level+;
} if (tn.Nodes.Count > )
{
myGetNodeLevels(tn.Nodes);
}
else
{
ColLists.Add(tn);//葉節點
}
} return iNodeLevels;
} /// <summary>調用遞歸求最大層數、列頭總高
///
/// </summary>
public void myNodeLevels()
{ iNodeLevels = ;//初始為1 ColLists.Clear(); int iNodeDeep = myGetNodeLevels(_ColHeaderTreeView.Nodes); iCellHeight = this.ColumnHeadersHeight; this.ColumnHeadersHeight = this.ColumnHeadersHeight * iNodeDeep;//列頭總高=一維列高*層數 } /// <summary>获得合并标题字段的宽度
///
/// </summary>
/// <param name="node">字段节点</param>
/// <returns>字段宽度</returns>
private int GetUnitHeaderWidth(TreeNode node)
{
int uhWidth = ;
//获得最底层字段的宽度
if (node.Nodes == null)
return this.Columns[GetColumnListNodeIndex(node)].Width; if (node.Nodes.Count == )
return this.Columns[GetColumnListNodeIndex(node)].Width; //获得非最底层字段的宽度
for (int i = ; i <= node.Nodes.Count - ; i++)
{
uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]);
}
return uhWidth;
} /// <summary>获得底层字段索引
///
/// </summary>
///' <param name="node">底层字段节点</param>
/// <returns>索引</returns>
/// <remarks></remarks>
private int GetColumnListNodeIndex(TreeNode node)
{
for (int i = ; i <= ColLists.Count - ; i++)
{
if (ColLists[i].Equals(node))
return i;
}
return -;
} ///<summary>绘制合并表头
///
///</summary>
///<param name="node">合并表头节点</param>
///<param name="e">绘图参数集</param>
///<param name="level">结点深度</param>
///<remarks></remarks>
public void PaintUnitHeader(
TreeNode node,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e,
int level)
{
//根节点时退出递归调用
if (level == )
return; RectangleF uhRectangle;
int uhWidth;
SolidBrush gridBrush = new SolidBrush(this.GridColor);
SolidBrush backColorBrush = new SolidBrush(e.CellStyle.BackColor);
Pen gridLinePen = new Pen(gridBrush);
StringFormat textFormat = new StringFormat(); textFormat.Alignment = StringAlignment.Center; uhWidth = GetUnitHeaderWidth(node); //与原贴算法有所区别在这。
if (node.Nodes.Count == )
{
uhRectangle = new Rectangle(e.CellBounds.Left,
e.CellBounds.Top + node.Level * iCellHeight,
uhWidth - ,
iCellHeight * (iNodeLevels - node.Level) - );
}
else
{
uhRectangle = new Rectangle(
e.CellBounds.Left,
e.CellBounds.Top + node.Level * iCellHeight,
uhWidth - ,
iCellHeight - );
} //画矩形
e.Graphics.FillRectangle(backColorBrush, uhRectangle); //划底线
e.Graphics.DrawLine(gridLinePen
, uhRectangle.Left
, uhRectangle.Bottom
, uhRectangle.Right
, uhRectangle.Bottom);
//划右端线
e.Graphics.DrawLine(gridLinePen
, uhRectangle.Right
, uhRectangle.Top
, uhRectangle.Right
, uhRectangle.Bottom); e.Graphics.DrawString(node.Text, this.ColumnHeadersDefaultCellStyle.Font
, Brushes.Black
, uhRectangle.Left + uhRectangle.Width / -
e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Width / -
, uhRectangle.Top +
uhRectangle.Height / - e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Height / ); //递归调用()
if (node.PrevNode == null)
if (node.Parent != null)
PaintUnitHeader(node.Parent, e, level - );
} #endregion //重寫表頭
protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
{
try
{
//行标题不重写
if (e.ColumnIndex < )
{
base.OnCellPainting(e);
return;
} if (iNodeLevels == )
{
base.OnCellPainting(e);
return;
} //绘制表头
if (e.RowIndex == -)
{
if (_ColHeaderTreeView != null)
{
if (iNodeLevels == )
{
myNodeLevels();
} PaintUnitHeader((TreeNode)this.ColLists[e.ColumnIndex], e, iNodeLevels); e.Handled = true;
}
else
{
base.OnCellPainting(e);
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Error");
}
}
}
}
using System;using System.Collections.Generic;using System.Text;using System.Windows.Forms;using System.Drawing;using System.ComponentModel;
namespace myMultiColHeaderDgv{ public class MultiColHeaderDgv:DataGridView {
#region 字段定義
/// <summary>多維列標題的樹結構 /// /// </summary> private TreeView _ColHeaderTreeView; /// <summary>樹的最大層數 /// /// </summary> private int iNodeLevels;
/// <summary>一維列標題的高度 /// /// </summary> private int iCellHeight;
/// <summary>所有葉節點 /// /// </summary> private IList<TreeNode> ColLists = new List<TreeNode>();
#endregion
#region 屬性定義
/// <summary>多維列標題的樹結構 /// /// </summary> [ Description("多維列標題的樹結構") ] public TreeView myColHeaderTreeView { get { return _ColHeaderTreeView; } set { _ColHeaderTreeView = value; } }
#endregion
#region 方法函數
/// <summary>遞歸計算樹最大層數,並保存所有葉節點 /// /// </summary> /// <param name="tnc"></param> /// <returns></returns> private int myGetNodeLevels(TreeNodeCollection tnc) { if (tnc == null) return 0;
foreach (TreeNode tn in tnc) { if ((tn.Level + 1) > iNodeLevels)//tn.Level是從0開始的 { iNodeLevels = tn.Level+1; }
if (tn.Nodes.Count > 0) { myGetNodeLevels(tn.Nodes); } else { ColLists.Add(tn);//葉節點 } }
return iNodeLevels; }
/// <summary>調用遞歸求最大層數、列頭總高 /// /// </summary> public void myNodeLevels() {
iNodeLevels = 1;//初始為1
ColLists.Clear();
int iNodeDeep = myGetNodeLevels(_ColHeaderTreeView.Nodes);
iCellHeight = this.ColumnHeadersHeight;
this.ColumnHeadersHeight = this.ColumnHeadersHeight * iNodeDeep;//列頭總高=一維列高*層數
}
/// <summary>获得合并标题字段的宽度 /// /// </summary> /// <param name="node">字段节点</param> /// <returns>字段宽度</returns> private int GetUnitHeaderWidth(TreeNode node) { int uhWidth = 0; //获得最底层字段的宽度 if (node.Nodes == null) return this.Columns[GetColumnListNodeIndex(node)].Width;
if (node.Nodes.Count == 0) return this.Columns[GetColumnListNodeIndex(node)].Width; //获得非最底层字段的宽度 for (int i = 0; i <= node.Nodes.Count - 1; i++) { uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]); } return uhWidth; }
/// <summary>获得底层字段索引 /// /// </summary> ///' <param name="node">底层字段节点</param> /// <returns>索引</returns> /// <remarks></remarks> private int GetColumnListNodeIndex(TreeNode node) { for (int i = 0; i <= ColLists.Count - 1; i++) { if (ColLists[i].Equals(node)) return i; } return -1; }
///<summary>绘制合并表头 /// ///</summary> ///<param name="node">合并表头节点</param> ///<param name="e">绘图参数集</param> ///<param name="level">结点深度</param> ///<remarks></remarks> public void PaintUnitHeader( TreeNode node, System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int level) { //根节点时退出递归调用 if (level == 0) return;
RectangleF uhRectangle; int uhWidth; SolidBrush gridBrush = new SolidBrush(this.GridColor); SolidBrush backColorBrush = new SolidBrush(e.CellStyle.BackColor); Pen gridLinePen = new Pen(gridBrush); StringFormat textFormat = new StringFormat();
textFormat.Alignment = StringAlignment.Center;
uhWidth = GetUnitHeaderWidth(node);
//与原贴算法有所区别在这。 if (node.Nodes.Count == 0) { uhRectangle = new Rectangle(e.CellBounds.Left, e.CellBounds.Top + node.Level * iCellHeight, uhWidth - 1, iCellHeight * (iNodeLevels - node.Level) - 1); } else { uhRectangle = new Rectangle( e.CellBounds.Left, e.CellBounds.Top + node.Level * iCellHeight, uhWidth - 1, iCellHeight - 1); }
//画矩形 e.Graphics.FillRectangle(backColorBrush, uhRectangle);
//划底线 e.Graphics.DrawLine(gridLinePen , uhRectangle.Left , uhRectangle.Bottom , uhRectangle.Right , uhRectangle.Bottom); //划右端线 e.Graphics.DrawLine(gridLinePen , uhRectangle.Right , uhRectangle.Top , uhRectangle.Right , uhRectangle.Bottom);
e.Graphics.DrawString(node.Text, this.ColumnHeadersDefaultCellStyle.Font , Brushes.Black , uhRectangle.Left + uhRectangle.Width / 2 - e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Width / 2 - 1 , uhRectangle.Top + uhRectangle.Height / 2 - e.Graphics.MeasureString(node.Text, this.ColumnHeadersDefaultCellStyle.Font).Height / 2);
//递归调用() if (node.PrevNode == null) if (node.Parent != null) PaintUnitHeader(node.Parent, e, level - 1); }
#endregion
//重寫表頭 protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e) { try { //行标题不重写 if (e.ColumnIndex < 0) { base.OnCellPainting(e); return; }
if (iNodeLevels == 1) { base.OnCellPainting(e); return; }
//绘制表头 if (e.RowIndex == -1) { if (_ColHeaderTreeView != null) { if (iNodeLevels == 0) { myNodeLevels(); }
PaintUnitHeader((TreeNode)this.ColLists[e.ColumnIndex], e, iNodeLevels);
e.Handled = true; } else { base.OnCellPainting(e); } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Error"); } } }}
【Winform-自定义控件】 DataGridView多维表头的更多相关文章
- (转)DataGridView多维表头及其扩展功能
dataGridView1.RowHeadersVisible = false;把整行选中那一列去掉.如果需要整行选中,新增一按钮列模拟实现.上源码:多维DataGridView 有个简易的方法: 1 ...
- C#中Winform程序中如何实现多维表头【不通过第三方报表程序】
问题:C#中Winform程序中如何实现多维表头. 在网上搜了很多方法,大多数方法对于我这种新手,看的都不是很懂.最后在新浪博客看到了一篇比较易懂的文章:[DataGridView二维表头与合并单元格 ...
- 【Winform-自定义控件】DataGridView 单元格合并和二维表头
DataGridView单元格合并和二维表头应用: //DataGridView绑定数据 DataTable dt = new DataTable(); dt.Columns.Add("); ...
- Datagridview 实现二维表头和行合并【转载】
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; u ...
- 如何通过DataGridView 实现单元格合并和二维表头
先看下实现出来的效果(这里随便写了几组数据,用来测试) 先初始一个DataGridView 设置哪几列 DataGridView 里男女这两列的 AutoSizeMode 可以设置Fill. publ ...
- (八十九)c#Winform自定义控件-自定义滚动条(treeview、panel、datagridview、listbox、listview、textbox)
官网 http://www.hzhcontrols.com/ 前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. GitHub:https://github.com/kw ...
- C#winform自定义控件大全
对C# WinForm开发系列收集的控件使用方面进行整理, 加入了一些文章, 不断补充充实, 完善这方面. 基础 - 常用控件 C# WinForm开发系列 - CheckBox/Button/Lab ...
- 关于Winform下DataGridView中实现checkbox全选反选、同步列表项的处理
近期接手一个winform 项目,虽然之前有.net 的经验,但是对一些控件的用法还不是很熟悉. 这段时间将会记录一些在工作中遇到的坎坷以及对应的解决办法,写出来与大家分享并希望大神提出更好解决方法来 ...
- (三十二)c#Winform自定义控件-表格
前提 入行已经7,8年了,一直想做一套漂亮点的自定义控件,于是就有了本系列文章. 开源地址:https://gitee.com/kwwwvagaa/net_winform_custom_control ...
随机推荐
- 什么是NameNode和DataNode?他们是如何协同工作的?
[学习笔记] 什么是NameNode和DataNode?他们是如何协同工作的? 马克-to-win @ 马克java社区:一个HDFS集群包含一个NameNode和若干的DataNode(start- ...
- hdu 4471 区间条件统计 区间 不超过 x 的元素的个数
题目传送门//res tp hdu 目的 对长度为n的区间,m次询问,每次提供一个区间两端点与一个值x,求区间内不超过x的元素个数 n 1e5 m 1e5 ai [1,1e9] (i∈[1,n]) 多 ...
- php用逗号格式化数字
今日工作需要格式化数字显示当前商品价格,比如2335.32,需要格式化为2,335.32这样显示.我写了一个函数.总感觉这么简单的功能,但是却需要30多行代码来完成. <?php/**** * ...
- PBOC第八部分和第十一部分关于TYPEA总结(二)——传输协议(ISO14443-4)
二.传输协议(ISO14443-4)(8,P50 11,P30) 1.选择应答请求(RATS) 使用RATS命令和PICC协商通讯的最大帧长度(FSD和FSC).帧等待时间(FWT)和启动帧保护时间( ...
- 01docker基本概念
docker基本概念 官方文档URL:https://docs.docker.com/ 1.Docker的构想是要实现"Build, Ship and Run Any App, Anywhe ...
- swagger 报错打不开
1.controller中的接口里使用的 qto的数据类型有问题: qo中的字段中缺少:(@JsonProperty(value = "sort"),以及定义的example值的格 ...
- Pytorch中randn和rand函数的用法
Pytorch中randn和rand函数的用法 randn torch.randn(*sizes, out=None) → Tensor 返回一个包含了从标准正态分布中抽取的一组随机数的张量 size ...
- warning C4819 的解决方法
编译VC++程序的时候出现如下提示警告: warning C4819: The file contains a character that cannot be represented in the ...
- svn安装方法
1.下载site-1.6.5svn插件 2.
- javascript立体学习指南
javascript立体学习指南第一章:首先了解javascript 首先,什么是javascript? JavaStrip出生于1995年,是一种文本脚本语言,成都装修公司是一种动态的.弱类型的.基 ...