[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");            }        }    }}

最新文章

  1. VMware Workstation 10.0 正式版官方简体中文下载(附序列号)
  2. highcharts的表名
  3. 视觉机器学习读书笔记--------BP学习
  4. VIM编辑新文件自动添加头文件信息
  5. double函数和int函数
  6. avalon2学习教程11数据联动
  7. 学习NGUI前的准备NGUI的相关信息
  8. SQL Server 修复数据库 相关 脚本 之 DBCC CHECKDB 用法 来自同事分享
  9. PHP 简易读取文件目录下的文件,生成css spirte图片
  10. MEMS微加工技术
  11. HDU 4726 Kia&#39;s Calculation (贪心算法)
  12. 真&#183;浅谈treap树
  13. HTML中META标签的使用
  14. 第16月第5天 performSelector afterDelay cancel dispatch_semaphore_wait
  15. ERP项目实施记录04
  16. 灰度发布:灰度很简单,发布很复杂&amp;灰度发布(灰度法则)的6点认识
  17. A Simple Problem with Integers---poj3468线段树
  18. 牛客练习赛16D K进制 数论(待理解QAQ)
  19. [Web前端]由cookies安全说开去
  20. Excel导入oracle库

热门文章

  1. codeforce C. Success Rate
  2. 5-Perl 变量
  3. Bootstrap3基础教程 02 网格布局
  4. js变量声明提升
  5. [转载]java的传值和传引用
  6. 如何使用koa搭建一个简单服务
  7. winfrom---Window 消息大全
  8. dubbo和zookeeper结合使用
  9. hbase shell 基本操作
  10. C++虚函数和纯虚函数的用法和区别