Fork me on GitHub

C# Datagridview combox列 初始化颜色

DataGridView 初始化完成后,在combox里显示颜色,如这样:
DataGridView 注册 cellPainting事件:
private void m_dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            var a = e.Value;

            if (a != null && LstColors.Contains(a))
            {
                var color = GetColorFromCode(a.ToString());

                var g = e.Graphics;
                Brush b=new SolidBrush(color);
                var rec = e.CellBounds;

                rec.X += 2;
                rec.Y += 2;
                rec.Width -= 20;
                rec.Height -= 10;

                
                e.PaintContent(rec);
                g.FillRectangle(b, rec);
                e.Handled = true;
            }


        }
public partial class Form1 : Form
    {
      
        private string xml =
                          @"<?xml version='1.0' standalone='yes'?>
                            <GenioCodes>
                              <Code No.='1'  name='A' Colour='Blue' />
                              <Code No.='2'  name='B' Colour='Green' />
                              <Code No.='3'  name='C' Colour='Red' />
                              <Code No.='4'  name='N' Colour='Black' />
                            </GenioCodes>";

        DataSet m_dataSet = new DataSet();
        List<ComboBox>ListCbx=new List<ComboBox>();
        public Form1()
        {
            InitializeComponent();

            // reading xml from string
            var reader = XmlReader.Create(new StringReader(xml));
            m_dataSet.ReadXml(reader);
            m_dataGridView.DataSource = m_dataSet.Tables[0];

            var column = m_dataGridView.Columns["Colour"];
            int idx = column.Index;
            // removing text column
            m_dataGridView.Columns.RemoveAt(idx);

            // adding comboBox column
            var cbo = new DataGridViewComboBoxColumn
            {
                Name = "color",
                DataPropertyName = "Colour",
            };
            // unique color codes for comboBox
            var colorCodes = m_dataSet.Tables[0].AsEnumerable()
                        .Select(r => r["Colour"])
                        .Distinct()
                        .ToList();
            cbo.DataSource = colorCodes;

            
            

            // restore column in orignal position
            m_dataGridView.Columns.Insert(idx, cbo);
            m_dataGridView.EditingControlShowing += ComboBoxShowing;


            //disallow adding and deleting rows
            m_dataGridView.AllowUserToAddRows = false;
            m_dataGridView.AllowUserToDeleteRows = false;




        }

        /// <summary>
        /// Activates custom drawing in comboBoxes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ComboBoxShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is ComboBox theCB)
            {
                theCB.DrawMode = DrawMode.OwnerDrawFixed;
                try
                {
                    theCB.DrawItem -= new DrawItemEventHandler(this.ComboItemDraw);
                  
                }
                catch { }
                theCB.DrawItem += new DrawItemEventHandler(this.ComboItemDraw);

                ListCbx.Add(theCB);
            }
        }

       

        /// <summary>
        /// Custom drawing for comboBox items
        /// </summary>
        private void ComboItemDraw(object sender, DrawItemEventArgs e)
        {
            Graphics g = e.Graphics;

            Rectangle rDraw = e.Bounds;
            rDraw.Inflate(-1, -1);

            bool bSelected = Convert.ToBoolean(e.State & DrawItemState.Selected);
            bool bValue = Convert.ToBoolean(e.State & DrawItemState.ComboBoxEdit);

            rDraw = e.Bounds;
            rDraw.Inflate(-1, -1);

            if (bSelected & !bValue)
            {
                g.FillRectangle(Brushes.LightBlue, rDraw);
                g.DrawRectangle(Pens.Blue, rDraw);
            }
            else
            {
                g.FillRectangle(Brushes.White, e.Bounds);
            }


            if (e.Index < 0)
                return;
            string code = ((ComboBox)sender).Items[e.Index].ToString();

            Color c = GetColorFromCode(code);
            string s = c.ToString();

            SolidBrush b = new SolidBrush(c);
            Rectangle r = new Rectangle(e.Bounds.Left, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height);
            g.FillRectangle(b, r);
            g.DrawRectangle(Pens.Black, r);
            //g.DrawString(s, Form.DefaultFont, Brushes.Black, e.Bounds.Left + 25, e.Bounds.Top + 1);

            b.Dispose();

        }
        List<String> LstColors = new List<string>() { "Blue", "Green", "Red", "Black" };
        /// <summary>
        /// Returns color for a given code 
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private Color GetColorFromCode(string code)
        {
            switch (code)
            {
                case "Blue": return Color.Blue;
                case "Green": return Color.Green;
                case "Red": return Color.Red;
                case "Black": return Color.Black;
            }
            return Color.Red;
        }
        int index;

        private void m_dataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            index = e.RowIndex;
            //实现单击一次显示下拉列表框
            if (m_dataGridView.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && e.RowIndex != -1)
            {
                SendKeys.Send("{F4}");
            }
        }

      

        private void m_dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            var a = e.Value;

            if (a != null && LstColors.Contains(a))
            {
                var color = GetColorFromCode(a.ToString());

                var g = e.Graphics;
                Brush b=new SolidBrush(color);
                var rec = e.CellBounds;

                rec.X += 2;
                rec.Y += 2;
                rec.Width -= 20;
                rec.Height -= 10;

                
                e.PaintContent(rec);
                g.FillRectangle(b, rec);
                e.Handled = true;
            }


        }
    }

来自问题:https://q.cnblogs.com/q/137678/#a_279065

posted @ 2022-01-01 08:50  HelloLLLLL  阅读(917)  评论(0编辑  收藏  举报