I am trying to create a custom ComboBox in c# Winforms for using with custom Highlight color. Found some examples from the internet and modified a little to keep my codes clean.But there is something wrong that i can not fix so i need your help.
here my custom ComboBox class:
using System.Drawing;
using System.Windows.Forms;
namespace TesTApp
{
class ThemedComboBox : ComboBox
{
protected Color _HighLightColor;
[System.ComponentModel.Description("High Light Color for selection"),
System.ComponentModel.Category("HighLight"),
System.ComponentModel.DefaultValue(typeof(Color), "Gray")]
public Color HighlightColor
{
get { return _HighLightColor; }
set
{
_HighLightColor = value;
Invalidate();
Update();
}
}
public ThemedComboBox()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
HighlightColor = Color.FromArgb(255, 167, 36);
this.DrawItem += new DrawItemEventHandler(ComboBox_DrawItem);
}
void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
return;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e.Graphics.FillRectangle(new SolidBrush(HighlightColor),
e.Bounds);
else
e.Graphics.FillRectangle(new SolidBrush(BackColor),
e.Bounds);
e.Graphics.DrawString(Items[e.Index].ToString(), e.Font,
new SolidBrush(ForeColor),
new Point(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
}
}
When i call the method for fill the ComboBox with List , DropDown does not display the names of items.
At first i created a class to fill the data
public class testItems
{
public string itemName { get; set; }
public int itemValue { get; set; }
}
And then i am calling the method that fills the ComboBox :
int maxItem = 5;
private void TestComboBox1()
{
List<testItems> _list = new List<testItems>();
for (int i = 0; i < maxItem; i++)
{
_list.Add(new testItems
{
itemName = "Item no: " + i.ToString(),
itemValue = i
});
}
themedComboBox1.DataSource = _list;
themedComboBox1.DisplayMember = "itemName";
themedComboBox1.ValueMember = "itemValue";
}
With this method , ComboBox DropDown does not display the name(DisplayMember) of items.
Then i have tried to fill ComboBox with a string array.With string array ComboBox displays the items but with this way i can not give values to items.
Here my method for fill the ComboBox with string array:
int maxItem = 5;
private void TestComboBox2()
{
string[] items = new string[maxItem];
for (int i = 0; i < maxItem; i++)
{
items[i] = "Item No : " + i;
}
themedComboBox2.DataSource = items;
}
All i want to have a custom ComboBox with custom Highlight color.Where am i doing wrong? Can you please help me to correct this?

