如何为DataGridViewComboBoxCell中的不同项设置字体颜色?例如,如果我有10个项目,我如何将项目3和5变成红色,而将其他项目变成黑色?
编辑:这是一个winform应用程序,DataGridViewComboBox不是数据绑定
edit2:也许我可以在editcontrolshow中这样做?
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name == "MyCombo")
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.CurrentCell;
for (int i = 0; i < comboCell.Items.Count; ++i)
{
string contract = comboCell.Items[i].ToString();
if (contract.ToUpper().Contains("NO"))
{
// can I set this item have a red font color???
}
}
}
对于行执行以下操作-挂钩OnRowDataBound事件,然后执行
ASPX(网格):
<asp:.... OnRowDataBound="RowDataBound"..../>
代码背后:
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1)
{
return;
}
if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
e.Row.BackColor=Color.Red;
}
}
对于WinForms:
hook the **DataBindingComplete** event and do stuff in it:
private void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
if (e.ListChangedType != ListChangedType.ItemDeleted)
{
DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
red.BackColor=Color.Red;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["FollowedUp"].Value.ToString()
.ToUpper().Contains("NO"))
{
r.DefaultCellStyle = red;
}
}
}
}
您需要手动绘制组合框项目。尝试以下操作(基于此MSDN文章):
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
// Note this assumes there is only one ComboBox column in the grid!
var comboBox = e.Control as ComboBox;
if (comboBox == null)
return;
comboBox.DrawMode = DrawMode.OwnerDrawFixed;
comboBox.DrawItem -= DrawGridComboBoxItem;
comboBox.DrawItem += DrawGridComboBoxItem;
}
private void DrawGridComboBoxItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index != -1)
{
// Determine which foreground color to use
var itemValue = actionsColumn.Items[e.Index] as string;
bool isNo = String.Equals("no", itemValue, StringComparison.CurrentCultureIgnoreCase);
Color color = isNo ? Color.Red : e.ForeColor;
using (var brush = new SolidBrush(color))
e.Graphics.DrawString(itemValue, e.Font, brush, e.Bounds);
}
e.DrawFocusRectangle();
}