Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
how to change font color of listbox selected items C# on button click

What I have tried:

for (int i = 0; i < lbProductsToBuy.Items.Count; i++)
{
lbProductsToBuy.SetSelected(i, true);
i.fontcolor = color.Red;
}
but it's not working
Posted
Updated 3-Aug-16 12:54pm
Comments
Afzaal Ahmad Zeeshan 3-Aug-16 21:51pm    
Integer has no definition for "fontcolor". Instead what you need to use is, the items collection and then select the item at ith index.

1 solution

You are trying to change the colour of an int I not the listbox item.

Use owner-draw mode of the ListBox. Select your ListBox in design-mode and change DrawMode property to OwnerDrawFixed. Now attach a handler to DrawItem event and then use Graphics class's methods to draw your string in any color or font you like. An example of what you need to do in DrawItem would be:
C#
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)

   MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
    if (item != null) 
    {
        e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            listBox1.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * listBox1.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
        );
    }
 
Share this answer
 
v5
Comments
Member 9983063 3-Aug-16 19:10pm    
lbProductsToBuy.Item[I].ForeGround = System.Drawing.Color.Red;
Sir it's not working
Member 9983063 3-Aug-16 19:14pm    
sir i want to change selected items forecolor change not background color
RossMW 3-Aug-16 19:14pm    
Sorry. Did a quick test and found the listbox cant do it natively so you have to dig into the bows of it. See update solution
RossMW 3-Aug-16 19:15pm    
Haven't tested personally. is foreground not a option?
Member 9983063 3-Aug-16 19:16pm    
yea there are 4 option equal gettype and getdatatype and tostring that's it

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900