I know that this code
C#
public void FillListBoxColoredText(ListBox LBx, List liststX)
{
int iCount = liststX.Count();
for (int ii = 0; ii < iCount; ii++) {
if (liststX[ii].Contains("blue"))
LBx.Items.Add(liststX[ii], Foreground = #0000ff);
else if (liststX[ii].Contains("red"))
LBx.Items.Add(liststX[ii], Foreground = #ff0000);
else if (liststX[ii].Contains("green"))
LBx.Items.Add(liststX[ii], Foreground = #00ff00);
}is not correct. It strives to indicate what I want.

Sarthak VarshneyRank #46 · 32K reputationPosted Mar 20, 2024, 12:40 AM EDT
To change the foreground color of items in a ListBox programmatically in C#, you can use the DrawItem event and customize the drawing of each item.
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace ListBoxColorChange { public partial class Form1 : Form { private ListBox listBox1; public Form1() { InitializeComponent(); InitializeListBox(); } private void InitializeListBox() { listBox1 = new ListBox(); listBox1.Dock = DockStyle.Fill; listBox1.DrawMode = DrawMode.OwnerDrawFixed; // Set draw mode to custom listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem); Controls.Add(listBox1); List items = new List { "Red", "Green", "Blue" }; foreach (string item in items) { listBox1.Items.Add(item); } } private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0) return; e.DrawBackground(); string itemText = listBox1.Items[e.Index].ToString(); // Set the text color based on the item text Color textColor = Color.Black; if (itemText.Contains("Red")) textColor = Color.Red; else if (itemText.Contains("Green")) textColor = Color.Green; else if (itemText.Contains("Blue")) textColor = Color.Blue; // Draw the item text with the determined color using (SolidBrush brush = new SolidBrush(textColor)) { e.Graphics.DrawString(itemText, e.Font, brush, e.Bounds, StringFormat.GenericDefault); } e.DrawFocusRectangle(); } } }the
listBox1_DrawItemevent handler is used to customize the drawing of each item in theListBox. It checks the text of each item and sets the colour accordingly. You'll need to adjust the colour logic to suit your specific requirements.Jayraj ChhayaRank #304 · 8.2K reputationPosted Mar 20, 2024, 3:45 AM EDT
Try this code
public void FillListBoxColoredText(ListBox LBx, List liststX) { int iCount = liststX.Count(); for (int ii = 0; ii < iCount; ii++) { if (liststX[ii].Contains("blue")) LBx.Items.Add(liststX[ii], System.Drawing.Color.Blue); else if (liststX[ii].Contains("red")) LBx.Items.Add(liststX[ii], System.Drawing.Color.Red); else if (liststX[ii].Contains("green")) LBx.Items.Add(liststX[ii], System.Drawing.Color.Green); } }