C# mark found TEXT in listbox in red

114 Views Asked by At

How can I mark a found TEXT in my listbox? First I'm searching for contain using this:

bool found = false;
 foreach (var item in listBox1.Items)
 {
     if(item.ToString().Equals("STOP"))
     {
         found = true;
         break;
     }
 }
if(!found)
    mark it in RED.

I want to highlight all the entire TEXT in red after finding the "STOP". Thank you!

1

There are 1 best solutions below

6
Antony Kao On BEST ANSWER

You should use the ListBox1_DrawItem to change the text color.

Sample Code:

public Form1()
{
    InitializeComponent();
    listBox1.DrawItem += ListBox1_DrawItem;
    listBox1.DrawMode = DrawMode.OwnerDrawFixed;

    // Sample Data
    listBox1.Items.Add("24 CALL LBL 1");
    listBox1.Items.Add("25 L X+100 Y-150 R0 FMAX M92");
    listBox1.Items.Add("26 STOP");
    listBox1.Items.Add("STOP");
}

private void ListBox1_DrawItem(object? sender, DrawItemEventArgs e)
{
    ListBox lb = (ListBox)sender;
    var itemText = lb.Items[e.Index].ToString();
    var textColor = Color.Black;
    if(itemText.Contains("STOP")) textColor = Color.Red;

    e.DrawBackground();
    Graphics g = e.Graphics;       
    g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(textColor), new PointF(e.Bounds.X, e.Bounds.Y));
    e.DrawFocusRectangle();
}

enter image description here

But I think ListView is better C# : changing listbox row color?