Autosizing ListView columns

 

horizontal rule

Back Home Next

Author Aart Onkenhout
Date 12-11-2000

 

Autosizing columns to match widest text within a column

 

When you want the columns within your reportview ListView have the width of the widest text within it, you can execute the following script after adding your columns (PB version 7.0 or later).

 

uLong    lul_Header, lul_LvHandle
Integer  li_ItemCount, li_Loop
Constant Integer LVM_GETHEADER = 4127
Constant Integer LVSCW_AUTOSIZE = -1
Constant Integer LVSCW_AUTOSIZE_USEHEADER = -2
Constant Integer HDM_GETITEMCOUNT = 4608

 

// First get a handle to the header of the listview. You can use this

// to get the number of columns within your ListView.

// A ListView actually exists of two controls, a ListView and a

// header control (when the ListView is in ListViewReport! mode).

// Columnheaders exists within the header control.

 

lul_LvHandle = Handle( yourListView )
lul_Header = Send( lul_LvHandle, LVM_GETHEADER, 0, 0 )

If lul_Header <= 0 Then Return

 

// Second, get the number of columns within the listview


li_ItemCount = Send( lul_Header, HDM_GETITEMCOUNT, 0, 0 )


/* Third, set the columnwidth of the columns.

   Indexes within ListView messages are zero-based so I start with column 0.

   Using the LVM_SETCOLUMNWIDTH message with the LVSCW_AUTOSIZE_USEHEADER

   value normally sizes your column to match the header width. For the

   last column however, it fills the REMAINING part of your ListView */

 

For li_Loop = 0 To li_ItemCount - 1
   Send( iul_lvHandle, LVM_SETCOLUMNWIDTH, li_Loop, LVSCW_AUTOSIZE_USEHEADER )
Next

Adding this code to the Resize-event ensures that the last column always fits exactly within the right border of the ListView.

When you use LVSCW_AUTOSIZE instead of LVSCW_AUTOSIZE_USEHEADER the last column will also be as wide as the widest text within that column.