Set the font and color of a listbox item by code i

2019-02-23 08:11发布

问题:

I'm busy with a customized list box that I use as a register reader in c#. Now I want to set a determined item in a determined item with a different font and color than the rest. I checked This question and from the answers I made the following code:

private void myListBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
    e.DrawBackground();
    Font myFont;
    Brush myBrush;
    int i = e.Index;

    if (e.Index == 3)
    {
        myFont = e.Font;
        myBrush = Brushes.Black;
    }
    else
    {
        myFont = new Font("Microsoft Sans Serif", 9.75f, FontStyle.Bold);
        myBrush = Brushes.CadetBlue;
    }

    e.Graphics.DrawString(myListBox.Items[i].ToString(), myFont, myBrush, e.Bounds, StringFormat.GenericDefault);
}

And call the method in my IntializeComponent() using

this.myListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.myListBox_DrawItem);

The call does not throw an exception whatsoever, but I see no change on the line I want to handle. Is there something I am missing?

回答1:

You are missing one more line in your IntializeComponent() add this:

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;

before attaching an event.