Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Resizable ListBox

0.00/5 (No votes)
26 Jan 2004 3  
A standard ListBox redrawing correctly when it is resized.

Introduction

You know that ListBox is a very useful component for displaying your style list with ownerdraw method. If you are using VariableSize mode to draw ListBox item, I think it will be interesting to you. All works fine if you are not going to change a ListBox's horizontal size. When you try to change ListBox's horizontal size, ListBox calls Draw for each visible item again, but problem is that it is not calling MeasureItems and your ListBox does not look like as you want..

Background

The MeasureItem event is raised when you add a new item to the list. So it occurs only once for each item. I have not found any direct way to call MeasureItem forcedly.

There are some indirect ways to solve this problem.

One of them is full reimplementation of ListBox control. See in the article "An auto-resize C# ListBox" By Christian Tratz.

The second way is to remove all items and add them again; as a result MeasureItems will be recalled for each item again. But if you have many items in your ListBox, this way is not the best one. You may have performance problems.

My solution is that when you need ReMeasuringItem, call code like this:

//  Forced Call MeasureItems.

listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
//

Using the code

Do not put this code in the ListBox resizing event. It will not work. Put it in ListBox's parent control. In my example, I put it in a form's event. For better performance, you may put it in SizeChanged event.

P.S. In my example, I demonstrate resizing ListBox by this way. In your code, you may wait until the form is resized and then allow to redraw ListBox items. Using this way, you will have better performance.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here