Reputation: 115
I have datagridview with DataGridComboboxColumn, I use CellFormating event to change cell color of this column:
private void dataTachesToday_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
Color c = Color.Pink;
if (e.ColumnIndex == 4)
{
switch (e.Value.ToString())//statut
{
case "A faire":
c = Color.DeepSkyBlue;
break;
case "En cours":
c = Color.HotPink;
break;
case "interrompue":
c = Color.Gold;
break;
case "Terminée":
c = Color.SpringGreen;
break;
case "Annulée":
c = Color.LightGray;
break;
}
e.CellStyle.ForeColor = c;
}
}
But when I click to select another item, all items take the same color of the cell, I want each item whith his specified color (maybe by using DropDownOpened event but this used for combobox not DataGridComboxColumn)
you can see here what is my problem:
Upvotes: 0
Views: 60
Reputation: 9771
First of all, add one event handler of EditingControlShowing
for DataGridView
either from the property window or from your Form_Load
.
private void Form_Load(object sender, EventArgs e)
{
dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;
}
Then add below code in EditingControlShowing
event handler,
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 1 && e.Control is ComboBox) //<= Specify your data grid view combo box column index instead of 1
{
ComboBox comboBox = e.Control as ComboBox;
comboBox.DrawMode = DrawMode.OwnerDrawFixed;
comboBox.DrawItem -= ComboBox_DrawItem;
comboBox.DrawItem += ComboBox_DrawItem;
}
}
And the main logic for changing color for each item in combo box column is,
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
Brush brush = null;
var g = e.Graphics;
if (e.Index >= 0)
{
string item = ((ComboBox)sender).Items[e.Index].ToString();
switch (item)
{
case "A faire":
brush = Brushes.DeepSkyBlue;
break;
case "En cours":
brush = Brushes.HotPink;
break;
case "interrompue":
brush = Brushes.Gold;
break;
case "Terminée":
brush = Brushes.SpringGreen;
break;
case "Annulée":
brush = Brushes.LightGray;
break;
}
g.DrawString(item, e.Font, brush, e.Bounds);
e.DrawFocusRectangle();
}
}
Output:
Upvotes: 1