winform DataGridView-----2

  上一篇对Data'gridView做了简单的封装,基本能满足正常开发了,后来我发现一个单元中同时会又左边图标右边文字的情况,这次就把这个也加上。所以我自定义歌一个组件。

  自定义  DataGridView 组件:

  

 public partial class GridList : DataGridView
    {
        private Dictionary<int, Image> dic { get; set; }

        public void SetHeader(List<dataGridViewModel> viewModel)
        {
            dic = new Dictionary<int, Image>();
            this.CellFormatting += Grid_cellFormartting;
            foreach (var item in viewModel)
            {
                switch (item.colType)
                {
                    case ColType.文本:
                        this.AutoGenerateColumns = false;
                        TextAndImageColumn ColumnRoleID = new TextAndImageColumn();
                        ColumnRoleID.DataPropertyName = item.colName;
                        ColumnRoleID.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                        ColumnRoleID.Name = item.colName;
                        ColumnRoleID.HeaderText = item.colTitle;
                        this.Columns.Add(ColumnRoleID);
                        break;
                    case ColType.图标://单独一列显示图标
                        this.SetImage();
                        break;
                    case ColType.图标文本://单独一列显示图标
                        SetCellImgOrText(item.cell);
                        break;
                    case ColType.按钮:
                        this.SetButton(item.TitleData);
                        break;
                    default:
                        break;
                }
            }
        }
        /// <summary>
        /// 设置图标文字
        /// </summary>
        /// <param name="cellType"></param>
         private void SetCellImgOrText(CellType cellType)
         {
            dic.Add(cellType.ColIndex, cellType.ImageType);
         }
         
        /// <summary>
        /// 列表添加图片
        /// </summary>
        private  void SetImage()
        {
            DataGridViewImageColumn Imange = new DataGridViewImageColumn();
            Imange.ImageLayout = DataGridViewImageCellLayout.Zoom;
            // Imange.HeaderText = "图标";
            this.Columns.Add(Imange);
        }
        /// <summary>
        /// 列表添加操作按钮
        /// </summary>
        /// <param name="gridView"></param>
        public  void SetButton( Title title)
        {
            if (title == null)
            {
                return;
            }
            DataGridViewButtonColumn select = new DataGridViewButtonColumn
            {
                Name = title.headTitle,
                Text = title.Text,
                UseColumnTextForButtonValue = true,
                DataPropertyName = "operate",
                FillWeight = 5,
                HeaderText = title.headText
            };
            select.FlatStyle = FlatStyle.Flat;
            select.Width = 20;
            select.DefaultCellStyle.ForeColor = string.IsNullOrEmpty(title.color) ? Color.Black : colorHx16toRGB(title.color);
            this.Columns.Add(select);
        }
        /// <summary>
        /// 设置隐藏某一列
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="colVisible"></param>
        public  void SetColVisible( string[] colVisible)
        {
            for (int i = 0; i < colVisible.Length; i++)
            {
                this.Columns[colVisible[i]].Visible = false;
            }

        }
        /// <summary>
        /// 对某些列进行列宽设置
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="colWidth"></param>
        public  void SetColWidth(Dictionary<int, int> colWidth)
        {
            foreach (int key in colWidth.Keys)
            {
                this.Columns[key].Width = colWidth[key];
            }
        }
        /// <summary>
        /// 表头颜色设置
        /// </summary>
        public  void SetHeadColor( string color)
        {
            //设置行表头的颜色
            this.EnableHeadersVisualStyles = false;
            this.ColumnHeadersDefaultCellStyle.BackColor = colorHx16toRGB(color);

        }
        /// <summary>
        /// 表头颜色设置
        /// </summary>
        public  void SetHeadColor(int R, int G, int B)
        {
            //设置行表头的颜色
            this.EnableHeadersVisualStyles = false;
            this.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(R, G, B);

        }
       
        /// <summary>
        /// 设置表头文字颜色
        /// </summary>

        public  void SetHeadFontColor( int R, int G, int B)
        {
            //表头文字颜色
            this.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(R, G, B);
        }
        /// <summary>
        /// 设置文字类型
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="fontType"></param>
        public  void SetHeadFontType( Font fontType)
        {
            //行表头文字类型
            this.ColumnHeadersDefaultCellStyle.Font = fontType;
        }
        /// <summary>
        /// 设置表头行高0
        /// </summary>
        /// <param name="gridView"></param>
        /// <param name="rowHeight"></param>
        public void SetHeadRowHeight( int rowHeight)
        {
            //改变标题的行高
            this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            this.ColumnHeadersHeight = rowHeight;
        }
        /// <summary>
        /// 居中标题
        /// </summary>
        public void SetHeadCenter()
        {
            this.AutoSize = false;
            //标题居中
           this.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }
        /// <summary>
        /// 去除第一列空列
        /// </summary>
        public void SetRowHeadersVisible()
        {
            this.RowHeadersVisible = false;

        }
        /// <summary>
        /// 去除最后一行空行
        /// </summary>
        public  void SetAllowUserToAddRows()
        {
            this.AllowUserToAddRows = false;
        }
        public  void SetCellRowFull()
        {
            this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }
        public GridList()
        {
            InitializeComponent();
            
        }

        private void Grid_cellFormartting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            foreach (int key in dic.Keys)
            {
                if (e.ColumnIndex==key)
                {
                    TextAndImageCell cell = this.Rows[e.RowIndex].Cells[e.ColumnIndex] as TextAndImageCell;
                    if (cell != null && e.Value != null)
                    {
                        try
                        {

                            cell.Image = dic[key];
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
           
        }

        public GridList(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }
        public Color colorHx16toRGB(string strHxColor)
        {
            try
            {
                if (strHxColor.Length == 0)
                {//如果为空
                    return Color.FromArgb(0, 0, 0);//设为黑色
                }
                else
                {//转换颜色
                    return Color.FromArgb(System.Int32.Parse(strHxColor.Substring(1, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(3, 2), System.Globalization.NumberStyles.AllowHexSpecifier), System.Int32.Parse(strHxColor.Substring(5, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
                }
            }
            catch
            {//设为黑色
                return Color.FromArgb(0, 0, 0);
            }
        }
    }

    public class TextAndImageColumn : DataGridViewTextBoxColumn
    {
        private Image imageValue;
        private Size imageSize;

        public TextAndImageColumn()
        {
            this.CellTemplate = new TextAndImageCell();
        }

        public override object Clone()
        {
            TextAndImageColumn c = base.Clone() as TextAndImageColumn;
            c.imageValue = this.imageValue;
            c.imageSize = this.imageSize;
            return c;
        }

        public Image Image
        {
            get { return this.imageValue; }
            set
            {
                if (this.Image != value)
                {
                    this.imageValue = value;
                    this.imageSize = value.Size;

                    if (this.InheritedStyle != null)
                    {
                        Padding inheritedPadding = this.InheritedStyle.Padding;
                        this.DefaultCellStyle.Padding = new Padding(imageSize.Width,
                    inheritedPadding.Top, inheritedPadding.Right,
                    inheritedPadding.Bottom);
                    }
                }
            }
        }
        private TextAndImageCell TextAndImageCellTemplate
        {
            get { return this.CellTemplate as TextAndImageCell; }
        }
        internal Size ImageSize
        {
            get { return imageSize; }
        }
    }

    public class TextAndImageCell : DataGridViewTextBoxCell
    {
        private Image imageValue;
        private Size imageSize;

        public override object Clone()
        {
            TextAndImageCell c = base.Clone() as TextAndImageCell;
            c.imageValue = this.imageValue;
            c.imageSize = this.imageSize;
            return c;
        }

        public Image Image
        {
            get
            {
                if (this.OwningColumn == null ||
           this.OwningTextAndImageColumn == null)
                {

                    return imageValue;
                }
                else if (this.imageValue != null)
                {
                    return this.imageValue;
                }
                else
                {
                    return this.OwningTextAndImageColumn.Image;
                }
            }
            set
            {
                if (this.imageValue != value)
                {
                    this.imageValue = value;
                    this.imageSize = value.Size;

                    Padding inheritedPadding = this.InheritedStyle.Padding;
                    this.Style.Padding = new Padding(imageSize.Width,
                   inheritedPadding.Top, inheritedPadding.Right,
                   inheritedPadding.Bottom);
                }
            }
        }
        protected override void Paint(Graphics graphics, Rectangle clipBounds,
       Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
       object value, object formattedValue, string errorText,
       DataGridViewCellStyle cellStyle,
       DataGridViewAdvancedBorderStyle advancedBorderStyle,
       DataGridViewPaintParts paintParts)
        {
            // Paint the base content
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
              value, formattedValue, errorText, cellStyle,
              advancedBorderStyle, paintParts);

            if (this.Image != null)
            {
                // Draw the image clipped to the cell.
                System.Drawing.Drawing2D.GraphicsContainer container =
               graphics.BeginContainer();

                graphics.SetClip(cellBounds);
                graphics.DrawImageUnscaled(this.Image, cellBounds.Location);

                graphics.EndContainer(container);
            }
        }

        private TextAndImageColumn OwningTextAndImageColumn
        {
            get { return this.OwningColumn as TextAndImageColumn; }
        }
    }

  Model:

 public enum ColType
    {
        文本,
        图标,
        图标文本,
        按钮
    }
  
    public class dataGridViewModel
    {
        public string colName { get; set; }
        public string colTitle { get; set; }
        public ColType colType { get; set; }
        public Title TitleData { get; set; }
        public CellType cell { get; set; }

    }
    /// <summary>
    /// 图标,文字
    /// </summary>
    public class CellType
    {
        public int ColIndex { get; set; }
        public Image ImageType { get; set; }

    }
    /// <summary>
    /// 按钮
    /// </summary>
    public class Title
    {
        public string headTitle { get; set; }
        public string Text { get; set; }
        public string headText { get; set; }
        public string color { get; set; }
    }

  实现:

从心编译工程,工具箱中会出现自定义控件:

 

 

//设置行表头的颜色
            //dataGridView_Mark.SetHeadColor("#F5F5F5");
            gridList1.SetHeadColor(250, 250, 250);
            //表头文字颜色
            //  dataGridView_File2.SetHeadFontColor("#F5F5F5");
            gridList1.SetHeadFontColor(95, 95, 95);
            //行表头文字类型
            gridList1.SetHeadFontType(new Font("楷体", 8, FontStyle.Bold));
            //改变标题的行高
            gridList1.SetHeadRowHeight(30);
            //去除第一列空列
            gridList1.SetRowHeadersVisible();
            //行占满
            gridList1.SetCellRowFull();
            //去除最后一行空行
            gridList1.SetAllowUserToAddRows();
            //标题居中
            gridList1.SetHeadCenter();
            List<dataGridViewModel> viewModel = new List<dataGridViewModel>()
            {
                new dataGridViewModel(){colType=ColType.图标},

                new dataGridViewModel(){colName="title",colTitle="标题",colType=ColType.图标文本,cell= new CellType(){ColIndex=2,ImageType=Properties.Resources.excel } },
                new dataGridViewModel(){colName="title1",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title2",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title3",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title4",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){colName="title5",colTitle="标题",colType=ColType.文本},
                new dataGridViewModel(){ colType = ColType.按钮,TitleData=new Title(){ headTitle="btnfile4",Text="按钮",headText="操作" } },
            };
            gridList1.SetHeader(viewModel);
            //设置某列隐藏
            // dataGridView_ReportList.SetColVisible(new string[] { "PKID", "customer" });
            Dictionary<int, int> colWidth = new Dictionary<int, int>()
            {
                [0] = 30,
                [6] = 60,
            };
            ////设置列宽
            gridList1.SetColWidth(colWidth);
            for (int i = 0; i < 30; i++)
            {
                gridList1.Rows.Add(Properties.Resources.excel, "dsf", "dfsfs", "dsfsdf", "dfsf", "dfsf", "dfsfs");

            }

  效果:

 

 项目中的效果图:

 

 

posted @ 2023-03-18 21:04  代码如风~~~  阅读(107)  评论(0编辑  收藏  举报