winform上的Combobox,combobox填充数据表三列(id,name,status)
combobox.displaymember = "name";
combobox.valuemember = "id";
我想更改状态列的组合框项目的颜色
请指教。
我能够做到这一点,但有一个错误。首先几步。
DrawItem
将comboBox1的事件更改为comboBox1_DrawItem
(我们下面的方法)Draw Mode
comboBox1 的属性更改为OwnerDrawFixed
或者OwnerDrawVariable
实施comboBox1_DrawItem
。请注意,我将画笔打开ComboBoxValue.Status
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
Brush brush;
var g = e.Graphics;
var rect = e.Bounds;
var n = "";
var f = new Font("Arial", 9, FontStyle.Regular);
switch (((ComboBoxValue)((ComboBox)sender).SelectedItem).Status)
{
case "one":
brush = Brushes.Red;
break;
case "two":
brush = Brushes.Green;
break;
default:
brush = Brushes.White;
break;
}
if (e.Index >= 0)
{
n = ((ComboBoxValue)((ComboBox)sender).SelectedItem).Name;
}
g.FillRectangle(brush, rect.X, rect.Y,rect.Width, rect.Height);
g.DrawString(n, f, Brushes.Black, rect.X, rect.Y);
}
我使用我自己的类的 IList 作为数据源。你的会有所不同。
public class ComboBoxValues : System.Collections.ObjectModel.Collection<ComboBoxValue>
{
public ComboBoxValues()
{
this.Add(new ComboBoxValue
{
Name = "chad",
Id = 123,
Status = "one"
});
this.Add(new ComboBoxValue
{
Name = "different chad",
Id = 123,
Status = "two"
});
}
}
public class ComboBoxValue
{
public string Name { get; set; }
public int Id { get; set; }
public string Status { get; set; }
}
设置您的DataSource
comboBox1.DataSource = new ComboBoxValues();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Id";
您很快就会看到的错误是,由于某种原因,颜色似乎只有在您将鼠标悬停在它们上之后才会发生变化。在我回到这个问题之前,也许其他人会意识到这个错误。祝你好运!