Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One word bold inside a text in winform control

I want some way to make a given word bold(the first two characters of each item in a listbox), and nothing else, something like this:

01 car
02 house
03 market

As for these three, being items in a listbox control, ALWAYS the first two characters, the rest should not be bold.

Is there any practical way for doing so ?

Data:

  • Visual Studio 2008
  • .NET 3.5

request:

    private void lstMaster_DrawItem(object sender, DrawItemEventArgs e)
    {
//TEST
        e.DrawBackground();
        Brush myBrush = Brushes.Black;
        Pen pen = new Pen(myBrush);
        e.Graphics.DrawRectangle(pen, 0, 0, 10, 10); //BREAKPOINT HERE

        e.Graphics.DrawString("aaa" + lstMaster.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);

        e.DrawFocusRectangle();

    }

It just keept the same, no rectangle, no "AAA", or square no breakpoint reached...

like image 229
Marcelo Avatar asked Feb 17 '10 11:02

Marcelo


1 Answers

It is possible, You will need to use the listbox's DrawItem event and from there you can draw your items however you would like to:

DrawItem event on MSDN

Here is an example that draws each item with different color:

private void ListBox1_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
  // Draw the background of the ListBox control for each item.
  e.DrawBackground();
  // Define the default color of the brush as black.
  Brush myBrush = Brushes.Black;

  // Determine the color of the brush to draw each item based 
  // on the index of the item to draw.
  switch (e.Index)
  {
      case 0:
          myBrush = Brushes.Red;
          break;
      case 1:
          myBrush = Brushes.Orange;
          break;
      case 2:
          myBrush = Brushes.Purple;
          break;
  }

  // Draw the current item text based on the current Font 
  // and the custom brush settings.
  e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), 
    e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
  // If the ListBox has focus, draw a focus rectangle around the selected item.
  e.DrawFocusRectangle();
 }

According to the documentation you will also need to change the DrawMode property of the listbox in order the fire the event:

This event is used by an owner-drawn ListBox. The event is only raised when the DrawMode property is set to DrawMode.OwnerDrawFixed or DrawMode.OwnerDrawVariable. You can use this event to perform the tasks needed to draw items in the ListBox.

like image 190
gyurisc Avatar answered Oct 30 '22 10:10

gyurisc