Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Can the last item in a Combo Drop down be colored Highlighted?
The need is to highlight the last item in a combo box (or list box if thats easier...)

What I have tried:

To fill the box:
C#
for (int i = 0; i < 10; i++)
{
    cboTest.Items.Add(i.ToString());
}

to get at last item in box
C#
cboTest.SelectedIndex = 9;

but that means you have to know the size, so if its variable can you do
C#
while (!((ArrayComPortsNames[index] == ComPortName) ||
                       (index == ArrayComPortsNames.GetUpperBound(0))));
Will GetUpperBound(0) get the first item I don't suppose there is GetLowerBound(), like cboTest.GetLowerBound()??
Posted
Comments
glennPattonWork3 20-Feb-24 5:53am    
I have come up with this:
private void button1_Click(object sender, EventArgs e)
{



for (int i = 0; i < 10; i++)
{
cboTest.Items.Add(i.ToString());
}

cboTest.SelectedIndex = cboTest.Items.Count-1;

}
to get the last item in a the box

How can you be sure there are 10 items in the combo? You should use the Count property of the Items collection. That way you can have any number of entries, and can always guarantee to find the last one. As to colouring the last one, take a look atComboBoxRenderer Class (System.Windows.Forms) | Microsoft Learn[^].
 
Share this answer
 
It depends what you mean by coloured as to how you would solve this (and I'm assuming you're using Windows Forms here). If you wanted to change the foreground colour, you could use something like this
C#
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{    
    e.DrawBackground();        
    ComboBox combobox = sender as ComboBox;

    string text = combobox.Items[e.Index].ToString();

    Brush brush;
    if (e.Index == combobox.Items.Length - 1) 
    {
        brush = Brushes.Red;
    }
    else
    {
        brush = Brushes.Black;
    }


    e.Graphics.DrawString(text, combobox.Font, brush, e.Bounds.X, e.Bounds.Y);
}
 
Share this answer
 
Comments
glennPattonWork3 20-Feb-24 14:19pm    
Cheers!
Pete O'Hanlon 20-Feb-24 14:34pm    
It's my absolute pleasure.
Maciej Los 20-Feb-24 16:03pm    
5ed!

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