简体   繁体   中英

Set the font and color of a listbox item by code in C#

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?

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

this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;

before attaching an event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM