我具有带有DataGridComboboxColumn的datagridview,我使用CellFormating事件来更改此列的单元格颜色:
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;
}
}
但是当我单击以选择另一个项目时,所有项目都采用与单元格相同的颜色,我希望每个项目都具有其指定的颜色(也许通过使用 DropDownOpened事件,但这用于组合框而不是DataGridComboxColumn )
答案 0 :(得分:1)
首先,从属性窗口或您的EditingControlShowing
中为DataGridView
添加一个Form_Load
的事件处理程序。
private void Form_Load(object sender, EventArgs e)
{
dataGridView1.EditingControlShowing += dataGridView1_EditingControlShowing;
}
然后在EditingControlShowing
事件处理程序中添加以下代码,
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;
}
}
更改组合框列中每个项目的颜色的主要逻辑是
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();
}
}
输出: