text color change in listbox control on winform

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello

I am trying to change the color of individual entry in the listbox control
based on some custom event. Can anyone please give any idea how to do it?

Thanks
 
Hi pothik05,

You need to handle the drawing for all items in the ListBox using DrawMode.OwnerDrawnFixed/Variable and the DrawItem event.

This sample uses a ListBox where one of the items in the list is the string "Two". This item will be colored Red and if selected highlighted with bold red.

private void listBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
Brush textBrush = SystemBrushes.ControlText;
Font drawFont = e.Font;

if(listBox1.Items[e.Index].ToString() == "Two")
{
textBrush = Brushes.Red;
if((e.State & DrawItemState.Selected) > 0)
drawFont = new Font(drawFont.FontFamily, drawFont.Size, FontStyle.Bold);
}
else if((e.State & DrawItemState.Selected) > 0)
{
textBrush = SystemBrushes.HighlightText;
}

e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), drawFont, textBrush, e.Bounds);
}

Instead of calling e.DrawBackGround you could customize your own background drawing code as well. Just remember to test for DrawItemState.Selected and use SystemBrushes.Highlight as the selected background color.
 
Thanks Morten. Actually I could do this. What I need to do is following:

After the Listbox is loaded, I have button and a text box. The text box
takes an input (the listitem index) and based on that input I need to change
the color to green of that listitem of the button's click event.

Thanks for your input.
 
Thanks Morten. Actually I could do this. What I need to do is following:

After the Listbox is loaded, I have button and a text box. The text box
takes an input (the listitem index) and based on that input I need to change
the color to green of that listitem of the button's click event.

Thanks for your input.
 
Thanks Morten. Actually I could do this. What I need to do is following:

After the Listbox is loaded, I have button and a text box. The text box
takes an input (the listitem index) and based on that input I need to change
the color to green of that listitem of the button's click event.

Thanks for your input.
 
Well, in that case you can just test for

if(e.Index.ToString() == textBox1.Text)
 
Thanks. It works. How do I make the the CheckedListBox work the same way. It
seems no to work.
 
Unlike what I said in another thread, and like someone else said in the same thread, create your own CheckedListBox version by inheriting from CheckedListBox and override the OnDrawItem event

class MyCheckedListBox : CheckedListBox
{
protected override void OnDrawItem(DrawItemEventArgs e)
{
// this code is called without specifying DrawMode
}
}
 
Back
Top