DevExpress.XtraGrid.GridControl控件运用小记(动态表头)、优化效果



 

 实现DevExpress.XtraGrid.GridControl控件表头的自定义绘制以及数据加载:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using DevExpress.XtraGrid.Views.BandedGrid;
using System.Drawing.Drawing2D;
using DevExpress.Utils.Drawing;
using UIControls;
namespace nxkj.fc.fm
{
    /// <summary>
    /// 该类实现树形接口目录以及型号的数据提供
    /// </summary>
   public class TreeViewTableHead
    {
       public enum NodeType
       {
           目录=0,
           型号=1
       }
       public enum TreeType
       {
           标准 = 0,
           设计 = 1,
           复测=2,
           复测400V=3
       }
       public enum StringDerection
       {
           水平 = 0,
           垂直 = 1
       }
       public enum ModelType
       {
           杆位编号=4,
           值类型=5,
           云网南网=6,
           杆型名称=7,
           接地棒=1,
           交叉跨=2,
           导线=3,
           默认=0
       }
       STDTYPE tp;
       System.Data.DataTable tableAllCatalog;
       System.Data.DataTable tableAllModels;
       TreeType viewChecktype;
       public TreeViewTableHead(STDTYPE stdtype, TreeType ctype)
       {
           viewChecktype = ctype;
           tp = stdtype;
           tableAllCatalog = new System.Data.DataTable();
           string sql = "select * from M_Catalog" + " where CatalogType like '%" + ((int)tp).ToString() + "%'";
           tableAllCatalog = nxkj.db.dataprovider.ProviderBase.QueryTableData(sql);
           sql = "select * from MaterialModels where MaterialModelType like '%" + ((int)tp).ToString() + "%'"; ;
           tableAllModels = nxkj.db.dataprovider.ProviderBase.QueryTableData(sql);
       }

       /// <summary>
       /// 返回树形结构数据
       /// </summary>
       public System.Windows.Forms.TreeView Head
       {
           get
           {
               TreeView viewhead = new TreeView();
               LoadConst(viewhead.Nodes, viewChecktype);
               if (tableAllCatalog == null || tableAllModels == null)
                   return viewhead;
               string filter = "ParentID='"+Guid.Empty.ToString()+"'";
               var rows = tableAllCatalog.Select(filter);
               
               foreach (DataRow item in rows)
               {
                   TreeNode node = new TreeNode();
                   NodeInfo n = new NodeInfo(
                       item["CatalogName"].ToString().Trim(),
                       item["M_Catalog_ID"].ToString().Trim(),
                       item["ParentID"].ToString().Trim(),
                       NodeType.目录
                       );
                   node.Tag = n;
                   node.Text = n.Title;
                   viewhead.Nodes.Add(node);
                   LoadChild(node);
               }
               return viewhead;
           }
       }

       void LoadChild(TreeNode node)
       {
           string filter = "ParentID='" + (node.Tag as NodeInfo).NodeID + "'";
           var rows = tableAllCatalog.Select(filter);
           if (rows.Length == 0)
           {
               LoadModels(node);
               return;
           }
           foreach (DataRow item in rows)
           {
               TreeNode nodesub = new TreeNode();
               nodesub.Text = item["CatalogName"].ToString().Trim();
                   NodeInfo n = new NodeInfo(
                       item["CatalogName"].ToString().Trim(),
                       item["M_Catalog_ID"].ToString().Trim(),
                       item["ParentID"].ToString().Trim(),
                       NodeType.目录
                       );
                   nodesub.Tag = n;
                   nodesub.Text = n.Title;
                   node.Nodes.Add(nodesub);
                   LoadChild(nodesub);
           }
       }

       void LoadModels(TreeNode node)
       {
           string filter = "M_Catalog_ID='" + (node.Tag as NodeInfo).NodeID + "'";
           var rows = tableAllModels.Select(filter);
           foreach (DataRow item in rows)
           {
               TreeNode nodesub = new TreeNode();
                   NodeInfo n = new NodeInfo(
                       item["MaterialModel"].ToString().Trim(),
                       item["MaterialModelID"].ToString().Trim(),
                       item["M_Catalog_ID"].ToString().Trim(),
                       NodeType.型号
                       );
                   int type = 0;
                   if (int.TryParse(item["XhLx"].ToString(), out type))
                   {
                       n.Mtype = (TreeViewTableHead.ModelType)type;
                   }
                   else
                   {
                       n.Mtype = ModelType.默认;
                   }
                   n.WordDeretion = StringDerection.垂直;
                   nodesub.Tag = n;
                   nodesub.Text = n.Title;
                   node.Nodes.Add(nodesub);
                   if (modelList.ContainsKey(n.Mtype))
                   {
                       modelList[n.Mtype].Add(n);
                   }
                   else
                   {
                       List<NodeInfo> list = new List<NodeInfo>();
                       list.Add(n);
                       modelList.Add(n.Mtype, list);
                   }
                   if (nodesub.Level > deep)
                       deep = nodesub.Level;
           }
       }
       Dictionary<TreeViewTableHead.ModelType, List<NodeInfo>> modelList = new Dictionary<ModelType, List<NodeInfo>>();

       /// <summary>
       /// 返回各个类型的型号类表
       /// </summary>
       public Dictionary<TreeViewTableHead.ModelType, List<NodeInfo>> Models
       {
           get
           {
               if (tableAllCatalog == null || tableAllModels == null)
                   return new Dictionary<ModelType, List<NodeInfo>>();
               return modelList;
           }
       }

       /// <summary>
       /// 加载常规表头
       /// </summary>
       /// <param name="nodes"></param>
       /// <param name="tpconst"></param>
       void LoadConst(TreeNodeCollection nodes, TreeType tpconst)
       {
           switch (tpconst)
           {
                   
               case TreeType.标准:
                   LoadConstNode("云网|南网", ModelType.云网南网, nodes);
                   LoadConstNode("杆型名称", ModelType.杆型名称, nodes);
                   break;
               case TreeType.复测:
                   LoadConstNode("杆位编号", ModelType.杆位编号, nodes);
                   LoadConstNode("值类型", ModelType.值类型, nodes);
                   LoadConstNode("云网|南网", ModelType.云网南网, nodes);
                   LoadConstNode("杆型名称", ModelType.杆型名称, nodes);
                   break;
               case TreeType.设计:
                   LoadConstNode("杆位编号", ModelType.杆位编号, nodes);
                   LoadConstNode("值类型", ModelType.值类型, nodes);
                   LoadConstNode("云网|南网", ModelType.云网南网, nodes);
                   LoadConstNode("杆型名称", ModelType.杆型名称, nodes);
                   break;
               case TreeType.复测400V:
                   LoadConstNode("杆位编号", ModelType.杆位编号, nodes);
                   LoadConstNode("接地棒", ModelType.接地棒, nodes);
                   LoadConstNode("值类型", ModelType.值类型, nodes);
                   LoadConstNode("云网|南网", ModelType.云网南网, nodes);
                   LoadConstNode("杆型名称", ModelType.杆型名称, nodes);
                   break;
           }
       }

       void LoadConstNode(string title,TreeViewTableHead.ModelType _tp,TreeNodeCollection nodes)
       {
           TreeNode node = new TreeNode();
           NodeInfo n = new NodeInfo(
               title, "", "", NodeType.目录
               );
           n.Mtype = _tp;
           node.Tag = n;
           node.Text = n.Title;
           nodes.Add(node);
           if (modelList.ContainsKey(n.Mtype))
           {
               modelList[n.Mtype].Add(n);
           }
           else
           {
               List<NodeInfo> list = new List<NodeInfo>();
               list.Add(n);
               modelList.Add(n.Mtype, list);
           }
       }

       int deep = 0;
       public int Deep
       {
           get
           {
               return deep;
           }
       }
       BandedGridView view;

       DevExpress.XtraGrid.GridControl Grid;
       public void BindToGrid(DevExpress.XtraGrid.GridControl grid)
       {
           var info = Head;
           Grid = grid;
           view = grid.DefaultView as BandedGridView;
           DataTable tb = new DataTable();
           foreach (var item in Models[ModelType.默认])
           {
               tb.Columns.Add(item.NodeID);
           }
           for (int i = 0; i < 100; i++)
           {

               DataRow r = tb.NewRow();
               for (int j = 0; j < tb.Columns.Count; j++)
               {
                   r[j] = j.ToString();

               }
               tb.Rows.Add(r);
           }
           view.CustomDrawBandHeader += new BandHeaderCustomDrawEventHandler(view_CustomDrawBandHeader);
           view.BeginUpdate();
           view.BeginDataUpdate();
           view.Bands.Clear();
           foreach (TreeNode item in Head.Nodes)
           {
               GridBand band = new GridBand();

               NodeInfo b = item.Tag as NodeInfo;
               band.Caption = b.Title;
               band.Tag = b;
               view.Bands.Add(band);
               LoadNode(item, band);
           }
           view.EndDataUpdate();
           view.EndUpdate();
           grid.DataSource = tb;
       }

       void LoadNode(TreeNode node, GridBand b)
       {

           foreach (TreeNode item in node.Nodes)
           {
               BandedGridColumn col = null;

               GridBand band = new GridBand();


               NodeInfo n = item.Tag as NodeInfo;

               band.Caption = n.Title;
               band.Tag = n;
               //加载列
               if (item.Nodes.Count == 0 && n.Ntype == TreeViewTableHead.NodeType.型号)
               {
                   col = new BandedGridColumn();
                   col.Caption = n.Title;
                   col.FieldName = n.NodeID;
                   col.Visible = true;
                   col.Width = 30;
                   view.Columns.Add(col);
                   band.Columns.Add(col);

               }
               if (n.WordDeretion == TreeViewTableHead.StringDerection.垂直)
               {
                   band.Width = 30;
                   if (item.Text == "名称")
                   {
                   }
                   if (item.Parent.Nodes.Count > 1)
                   {
                       try
                       {
                           Graphics g = Graphics.FromHwnd(Grid.Handle);
                           g.PageUnit = GraphicsUnit.Pixel;
                           g.SmoothingMode = SmoothingMode.HighQuality;
                           StringFormat sf = new StringFormat();
                           sf.FormatFlags = StringFormatFlags.MeasureTrailingSpaces;
                           SizeF sizeF = g.MeasureString(item.Parent.Text,Grid.Font, 500, sf);
                           if (item.Parent.Nodes.Count * 30 < (sizeF.Width + 10))
                           {
                               band.Width = (int)(sizeF.Width / item.Parent.Nodes.Count) + 10;
                               if (item.Nodes.Count == 0 && n.Ntype == TreeViewTableHead.NodeType.型号)
                               {
                                   col.Width = (int)(sizeF.Width / item.Parent.Nodes.Count) + 10;
                               }
                           }
                       }
                       catch
                       {
                       }
                   }

               }
               else if (item.Nodes.Count == 1)
               {
                   n.WordDeretion = TreeViewTableHead.StringDerection.垂直;
               }
               b.Children.Add(band);
               if (item.Nodes.Count == 0 && item.Parent.Nodes.Count > 1)
               {
                   band.RowCount = (Deep - item.Parent.Level) * 2 + 1;
               }
               else if (n.Ntype == TreeViewTableHead.NodeType.目录 && item.Nodes.Count == 1)
               {
                   n.WordDeretion = TreeViewTableHead.StringDerection.垂直;
                   if (n.Title.Length > 3)
                   {
                       band.RowCount = n.Title.Length - 1;
                   }
                   else
                   {
                       band.RowCount = 3;
                   }

               }
               LoadNode(item, band);
           }

       }

       void view_CustomDrawBandHeader(object sender, BandHeaderCustomDrawEventArgs e)
       {
           NodeInfo node = e.Band.Tag as NodeInfo;

           //A brush to fill the band's background in the normal state
           Brush brush = new LinearGradientBrush(e.Bounds, Color.White, Color.Silver, 100);
           //A brush to fill the background when the band is pressed
           Brush brushPressed = new LinearGradientBrush(e.Bounds,
             Color.WhiteSmoke, Color.Gray, 70);
           Rectangle r = e.Bounds;

           //Draw a 3D border
           ControlPaint.DrawBorder3D(e.Graphics, r, (e.Info.State == ObjectState.Pressed ?
            Border3DStyle.SunkenOuter : Border3DStyle.RaisedInner));
           r.Inflate(-1, -1);
           //Fill the background
           e.Graphics.FillRectangle(brush, r);
           r.Inflate(-2, 0);
           //Draw the band's caption with a shadowed effect
           StringFormat f = new StringFormat();



           f.LineAlignment = StringAlignment.Center;
           f.FormatFlags |= StringFormatFlags.NoWrap;
           if (node.WordDeretion == TreeViewTableHead.StringDerection.垂直)
           {
               f.FormatFlags |= StringFormatFlags.DirectionVertical;
               f.Alignment = StringAlignment.Near;
           }
           else
           {
               f.Alignment = StringAlignment.Center;
           }
           //  f.FormatFlags |= StringFormatFlags.DisplayFormatControl;
           // f.FormatFlags = StringFormatFlags.NoWrap;
           // e.Appearance.DrawString(e.Cache, e.Band.Caption, new Rectangle(r.X + 1, r.Y + 1,
           // r.Width, r.Height), Brushes.White,f);
           //  e.Appearance.DrawString(e.Cache, e.Band.Caption, r, Brushes.Black,f);
           //Prevent default painting
           e.Graphics.DrawString(node.Title,e.Band.View.GridControl.Font, System.Drawing.Brushes.Black, r, f);
           e.Handled = true;
       }
    }

    /// <summary>
    /// 节点信息
    /// </summary>
   public class NodeInfo
   {
       public NodeInfo(string _title,string _nodeID,string _parentID,TreeViewTableHead.NodeType _ntype)
       {
           Title = _title.Replace("\r\n","");
           NodeID = _nodeID;
           ParentID = _parentID;
           Ntype = _ntype;
       }

       /// <summary>
       /// 标题
       /// </summary>
       public string Title { get; set; }

       /// <summary>
       /// 节点编号
       /// </summary>
       public string NodeID { get; set; }

       /// <summary>
       /// 父级编号
       /// </summary>
       public string ParentID { get; set; }

       /// <summary>
       /// 目录类型
       /// </summary>
       public TreeViewTableHead.NodeType Ntype
       {
           get;
           set;
       }
       public override string ToString()
       {
           return Title;
       }

       /// <summary>
       /// 列类型
       /// </summary>
       public TreeViewTableHead.ModelType Mtype
       {
           get;
           set;
       }

       /// <summary>
       /// 文字方向
       /// </summary>
       public TreeViewTableHead.StringDerection WordDeretion
       {
           get;
           set;
       }
   }
}

猜你喜欢

转载自lxjlfy.iteye.com/blog/1614900