DataGridView实现自定义颜色列模板

最终展示结果如下:

1、ColorPickerColumn 该扩展组件为国外牛人开源的

2、需要编译成32位

    public class ColorPickerColumn : DataGridViewColumn
    {
        public ColorPickerColumn():base(new ColorPickerCell())
        {
        
        }

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                // Ensure that the cell used for the template is a CalendarCell.
                if (value != null && 
                    !value.GetType().IsAssignableFrom(typeof(ColorPickerCell)))
                {
                    throw new InvalidCastException("Must be a ColorPicker");
                }
                base.CellTemplate = value;
            }
        }
    }

    public class ColorPickerCell : DataGridViewTextBoxCell 
    {
        ColorPickerControl _ColorPicker;
        public ColorPickerCell()
            : base()
        {
        
           
        }
      
        public override void InitializeEditingControl(int rowIndex, object
            initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue,
                                          dataGridViewCellStyle);
            ColorPickerControl ctl = DataGridView.EditingControl as ColorPickerControl;
            _ColorPicker = ctl;
            
            if (this.Value !=null && (this.Value.GetType() == typeof(Color)))
            {
                ctl.Color = (Color)this.Value;
            }
        }

        public override Type EditType
        {
            get
            {
               //Return the type of the editing contol that CalendarCell uses.
             return typeof(ColorPickerControl);
            }
        }
    
        public override Type ValueType
        {
            get
            {
                // Return the type of the value that CalendarCell contains.
               return typeof(Color);
            }
        }
        
        public override object DefaultNewRowValue
        {
            get
            {
                // Use the current date and time as the default value.
                return Color.White;
            }
        }
     
        protected override void Paint(Graphics graphics,
                                        Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
                                        DataGridViewElementStates elementState, object value,
                                        object formattedValue, string errorText,
                                        DataGridViewCellStyle cellStyle,
                                        DataGridViewAdvancedBorderStyle advancedBorderStyle,
                                        DataGridViewPaintParts paintParts)
        {
            formattedValue = null;
            
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue,
                       errorText, cellStyle, advancedBorderStyle, paintParts);

           
            Rectangle ColorBoxRect = new Rectangle();
            RectangleF TextBoxRect = new RectangleF();
            GetDisplayLayout(cellBounds, ref ColorBoxRect, ref TextBoxRect);

             Draw the cell background, if specified.
            if ((paintParts & DataGridViewPaintParts.Background) ==
                DataGridViewPaintParts.Background)
            {
                SolidBrush cellBackground;
                if (value != null && value.GetType() == typeof(Color))
                {
                    cellBackground = new SolidBrush((Color)value);
                }
                else
                {
                    cellBackground =  new SolidBrush(cellStyle.BackColor);
                }
                graphics.FillRectangle(cellBackground, ColorBoxRect);
                graphics.DrawRectangle(Pens.Black, ColorBoxRect);
                Color lclcolor=(Color)value;
                graphics.DrawString(lclcolor.Name.ToString(), cellStyle.Font, System.Drawing.Brushes.Black, TextBoxRect);
            
                cellBackground.Dispose();
            }
                
        }

        public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, System.ComponentModel.TypeConverter formattedValueTypeConverter, System.ComponentModel.TypeConverter valueTypeConverter)
        {
            int result;
            string number = "0x" + formattedValue.ToString();
            if (int.TryParse(formattedValue.ToString(), System.Globalization.NumberStyles.HexNumber, null, out result))
                //Hex number
                return base.ParseFormattedValue("0x" + formattedValue.ToString(), cellStyle, formattedValueTypeConverter, valueTypeConverter);
            else
                return base.ParseFormattedValue(formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter);
        }

        protected virtual void GetDisplayLayout(Rectangle CellRect,ref Rectangle colorBoxRect, ref RectangleF textBoxRect)
        {
            const int DistanceFromEdge = 2;
           
            colorBoxRect.X = CellRect.X+DistanceFromEdge ;
            colorBoxRect.Y = CellRect.Y +1 ;
            colorBoxRect.Size = new Size((int)(1.5 * 17), CellRect.Height - (2*DistanceFromEdge));

            // The text occupies the middle portion.
            textBoxRect = RectangleF.FromLTRB(colorBoxRect.X + colorBoxRect.Width + 5, colorBoxRect.Y+2, CellRect.X+CellRect.Width-DistanceFromEdge , colorBoxRect.Y + colorBoxRect.Height  );
        }
    }

    class ColorPickerControl : LaMarvin.Windows.Forms.ColorPicker, IDataGridViewEditingControl
    {
        DataGridView dataGridView;
        private bool valueChanged = false;
        int rowIndex;
       
        public ColorPickerControl()
        {
            
        }

        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
                return this;
            }
            set
            {
                this.Color = Color.Pink;
            }
        }

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
        {
            return Color.Name;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(
            DataGridViewCellStyle dataGridViewCellStyle)
        {
            this.Font = dataGridViewCellStyle.Font;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex
        {
            get
            {
                return rowIndex;
            }
            set
            {
                rowIndex = value;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(
            Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    return true;
                default:
                    return !dataGridViewWantsInputKey;
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView EditingControlDataGridView
        {
            get
            {
                return dataGridView;
            }
            set
            {
                dataGridView = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged
        {
            get
            {
                return valueChanged;
            }
            set
            {
                valueChanged = value;
            }
        }

        // Implements the IDataGridViewEditingControl
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected virtual void NotifyDataGridViewOfValueChange()
        {
            this.valueChanged = true;
            if (this.dataGridView != null)
            {
                this.dataGridView.NotifyCurrentCellDirty(true);
            }
        }

        protected override void OnLeave(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            base.OnLeave(eventargs);
            NotifyDataGridViewOfValueChange();
        }

    }

源码路径:https://download.csdn.net/download/wokao253615105/16490615

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 基类说明 1.1 基类结构图 1.2 基类说明 1.2.1 BaseEditClass BaseEditClass是所有单表编辑功能的基类。BaseEditClass从NSGForm继承,以处理统一的界面和字体风格。 BaseEditClass抽象出了编辑类功能通用的方法并定义为基类方法,以便子类继承,并增加自己的代码。  自定义属性 名称 说明 DataTable 功能所编辑的数据表 DataState 功能所处的状态:浏览(dsBrowse)、新增(dsInsert)、编辑(dsEdit) BatchSave 是否批量提交数据表,默认为False DeleteWarn 在删除记录时是否提示,默认为True  自定义方法 名称 说明 FormInit 在FormLoad时被调用,具体功能中可重载该方法添加自定义的初始化代码 PostData 具体功能中需要重载该方法,并调用具体的TableAdapter.Update(row),以保存数据至数据库。 RefreshData 统一的刷新数据表过程,具体功能中需要重载该方法,并调用具体的TableAdapter.Fill(DataTable),以查询数据 DataValid 统一的数据验证方法,在保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 NewRecord 在新增数据时被调用,在具体过程中可重载该方法添加自定义的新增记录默认值 SaveData 保存数据的方法,具体功能中调用该过程保存数据 DeleteData 删除数据的方法,具体功能中调用该过程删除数据 CancelData 取消数据修改的方法,具体功能中调用该过程取消数据修改 1.2.2 BaseGridEdit BaseGridEdit是所有直接使用DataGridView进行编辑的功能的基类。BaseGridEdit从BaseEditClass继承。 自定义属性 名称 说明 Grid 编辑所用的DataGridView 自定义方法 名称 说明 RecordValid 统一的数据验证方法,在单条保存数据前被调用。具体功能中可重载该方法添加自定义的数据校验代码 1.2.3 BaseGridEditForm BaseGridEditForm是所有直接使用DataGridView进行编辑的功能的模板。所有直接使用DataGridView进行编辑的功能都需要从该模板拷贝后进行修改。 2. 模板使用方法 2.1 BaseGridEditForm 使用BaseGridEditForm需要按以下四步操作就可以得到需要的功能。 一、 先从BaseGridEditForm拷贝文件到工程后修改类名、命名空间 二、 在项目的数据集中增加TableAdapter,以查询需要维护的指定的数据表 三、 将DataGridView绑定到新增的数据表 四、 修改以下基类方法 名称 说明 构造方法 增加”DataTable属性=新增数据表”的代码 FormInit 增加需要的Form初始化代码,如RefreshData以获得数据 PostData 增加一行代码:新增的TableAdapter.Update(row) RefreshData 增加使用新增TableAdapter.Fill(DataTable)的代码,以获得查询数据。注意:代码需要写在IsRefreshData = true;和 IsRefreshData = false;语句的中间 RecordValid 增加自定义的数据校验语句。 NewRecord 增加自定义的新增数据默认值代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xizhjxust_GIS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值