How do I change the displayed text color of individual list box items?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sal Sal
    New Member
    • Nov 2010
    • 15

    #1

    How do I change the displayed text color of individual list box items?

    Hi I have a listbox that I am adding files to it. If the user checks a specific radiobutton when adding the item, I want to color the text with some color -- but only the text for that item, not all the items. The problem I am having is that my code colors all the items the same. Anyone know a simple way to do this?

    The objects the user is adding to the listbox are files
    and I want to display the Name of the file in the listbox, but I encounter two problems

    1 - I cannot add an item with a color different from the other items in the listbox (they all have the same color)

    2 - When drawing the text I cannot get the 'Name' property to be displayed. So if I add a custom class object to the list, all I see is the namespace.class name for all items.

    Code:
    //Draw Item function
    
            private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
            {
                e.DrawBackground();
    
                Graphics g = e.Graphics;
                ListBox lb = (ListBox)sender;
                g.DrawString(lb.Items[e.Index].ToString(), e.Font, new SolidBrush(radiobutton1.Checked==true?Color.Green:Color.Red), new PointF(e.Bounds.X, e.Bounds.Y)); 
                e.DrawFocusRectangle();
            }
    
    //add items
    
     private void addButton_Click(object sender, EventArgs e) 
            {
                    //test.Substring(2, 5);
                    int size = -1;
                    // Show the dialog and get result.
                    DialogResult result = openFileDialog1.ShowDialog();
                    if (result == DialogResult.OK) // Test result.
                    {
                        string[] files = openFileDialog1.FileNames; //list of files selected
    
                        foreach (string file in files)
                        {
                            System.IO.FileInfo f = new System.IO.FileInfo(file);
                            if (listBox1.FindString(f.Name) == -1)
                            {
    				
    				listBox1.DrawMode = DrawMode.OwnerDrawVariable;
                                    listBox1.DrawItem += listBox1_DrawItem;
                                	listBox1.Items.Add(f);
                                	listBox1.DisplayMember = "Name";
    			
                            }
    
                        }
    
                    }
    }
  • Sal Sal
    New Member
    • Nov 2010
    • 15

    #2
    Answer is located here

    The home for technical questions and answers at Microsoft. Get started asking, answering, and browsing questions about products like .Net, Azure, or Teams.

    Comment

    Working...