winform上的Combobox, 组合框填充数据表三列(id,name,status)
combobox.displaymember = "name";
combobox.valuemember = "id";
我想更改状态列
的Combobox项目的颜色请建议。
答案 0 :(得分:3)
我能够做到这一点,但有一个错误。 首先是几步。
DrawItem
事件更改为comboBox1_DrawItem
(我们的方法如下)Draw Mode
属性更改为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";
这个错误,你很快就会看到,由于某种原因,只有在鼠标悬停在它们之后颜色似乎才会改变。也许别人会在我回到这个之前意识到这个错误。祝你好运!