Saturday, February 11, 2006

"Autosize the last column in a ListView control using WndProc"

Autosize the last column in a ListView control using WndProc - The Code Project - C# Controls

"It has always been a pet-peeve of mine, that I prefer grid or list controls to auto size their columns to fit the control canvas. Some of you may remember the early OCX and ActiveX controls that implemented auto-size last column properties to resolve this problem. Essentially, the last column in the grid or list view is automatically expanded to take up any available space. As the form is resized, or column widths are resized by the user at runtime, the last column size is automatically increased or decreased to keep the column aligned with the control right edge.

In fact, the ListView class does provide a ColumnHeader.Width property. The MSDN documentation describes two special values related to auto-sizing the column, as follows: "To adjust the width of the longest item in the column, set the Width property to -1. To auto size to the width of the column heading, set the Width property to -2".

A special feature of setting the Width to -2, is that it ALSO automatically expands the last column to the right-edge of the control. This would seem to solve the problem, except that it does it a one-time auto-size that is not preserved if the user resizes any of the column widths at runtime, or the ListView control is set to resize with the form.

…"

This is a better way of implementing this (last column in a listview expanded to fill control) than I’ve used, so I’m noting it here.

And again I’ve learned something new. The special ColumnHeader.Width = -1 or -2 settings are cool… (So much easier than calc’ing the width based on control size, size of other columns, etc… yeah, I did it the hard way before… sigh)

No comments: