N
N
nubic2017-02-15 11:19:08
.NET
nubic, 2017-02-15 11:19:08

How to color combobox column in datagridview c#?

Hello! I use this code to color rows in comboboxes in the datagrid:

private void dgvMain_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
          if (e.Control is ComboBox)
            {
                ComboBox cmb = e.Control as ComboBox;
                cmb.DrawMode = DrawMode.OwnerDrawFixed;
                cmb.DrawItem -= new DrawItemEventHandler(cbStatus_DrawItem);
                cmb.DrawItem += new DrawItemEventHandler(cbStatus_DrawItem);
            }
        }
private void cbStatus_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (sender is ComboBox)
            {
                e.DrawBackground();
                ComboBox currComboBox = (ComboBox)sender;
                DataRowView currIntemDRView = (DataRowView)currComboBox.Items[e.Index];
                string text = currIntemDRView.Row["status_name"].ToString();
                int id = Convert.ToInt32(currIntemDRView.Row["id_status"]);
                int type = 0;
                foreach (DataRow currRow in Status.Rows)
                {
                    int currId = (int)currRow["id_status"];

                    if (currId == id)
                    {
                        type = (int)currRow["id_status"];
                        break;
                    }
                }

                // определяем цвет для текущей строки 
                Brush brush;
                Brush brush2 = Brushes.Black;
                if (type == 1)
                {
                    brush = Brushes.White;
                    brush2 = Brushes.Black;
                }
                else if (type == 2)
                {
                    brush = Brushes.Green;
                    brush2 = Brushes.White;
                }
                else if (type == 3)
                {
                    brush = Brushes.Yellow;
                    brush2 = Brushes.Black;
                }
                else if (type == 4)
                {
                    brush = Brushes.Pink;
                    brush2 = Brushes.Black;
                }
                else if (type == 5)
                {
                    brush = Brushes.Red;
                    brush2 = Brushes.White;
                }
                else brush = Brushes.Gold;
                
                e.Graphics.FillRectangle(brush, e.Bounds.X, e.Bounds.Y, 200, 15);
                e.Graphics.DrawString(text, currComboBox.Font, brush2, e.Bounds.X, e.Bounds.Y);

            }
        }

But when you click on other cells in the datagrid, the color disappears. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question