65.9K
CodeProject is changing. Read more.
Home

An auto-resize C# Listbox (updated)

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.74/5 (13 votes)

Jun 22, 2004

viewsIcon

179815

downloadIcon

4747

A listbox which will auto-resize its texts.

Sample image

Sample image

Introduction

This is generally an extended version of the auto-resize C# Listbox by Christian Tratz. He didn't have the time to post this version, so I wrote this very short article. The improvements are '\n' support, now and then words got to the right edge, the line (integer) is changed to string to allow custom values in the header. That's it, have fun!

Using the code

See Christian Tratz' article on this, nothing changed. However if you use the Item.Insert instead of Item.Add selected items will now move to the bottom (when something is inserted above, of course). See also the example provided above. In short:

// Create the Listbox..
listbox = new ListBox.MessageListBox();
listbox.Size = new Size( this.ClientSize.Width, this.ClientSize.Height);
listbox.Dock = DockStyle.Top;

// .. and add it to the controls.
this.Controls.Add( listbox);

Then, you can start adding messages to the end of the listbox:

listbox.Items.Add(
 new ListBox.ParseMessageEventArgs(
  ListBox.ParseMessageType.Info,
  "Info1",
  "Some information.. there should be enough text in this area
   to see that the resizing works! The text is wrapped in between
   words as much as possible, since this control has no knowledge
   of words. However, when not possible the words are split."));

Or, insert them at an index:

listbox.Items.Insert(
 1, 
 new ListBox.ParseMessageEventArgs(
  ListBox.ParseMessageType.None,
  "Some more info",
  "Text can also be inserted at any index. Previously selected
   text will e.g. move to the bottom when something is inserted
   above."));

After that, redraw the control:

listbox.Invalidate();

History

  • Version 1.2 - Optimized the drawing method: only the visible items are drawn and measuring only takes place after a resize.
  • Version 1.1 - First Version