This topic shows you how to autofit all columns in a Listview control to it contents.
This document has been viewed times since February 22, 1998.
Last modified on February 22, 1998.
'At top level of a module, always include to be sure that all variables have the right type
'Then declare these constants. LVM_FIRST is base code
Private Const LVM_FIRST As Long = &H1000
'LVM_SETCOLUMNWIDTH constant tells Windows to handle column width
Private Const LVM_SETCOLUMNWIDTH As Long = LVM_FIRST + 30
'LVSCW_AUTOSIZE_USEHEADER is used to tell Windows that the column heads are to be resized
Private Const LVSCW_AUTOSIZE_USEHEADER As Long = -2
'Then decleare SendMessage for sending Windows message in order to autofit Listview Control
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
'Then all we have to do is to write a public sub like this...
Public Sub lvwAutofitColumnWidth(ByVal lvw As ComctlLib.ListView)
'Declare a counter variable iCounter
Dim iCounter As Long
'Turn on error trapping
On Error Resume Next
'Check the current view for the ListView Control. If not in report view then exit here
If lvw.View <> lvwReport Then Exit Sub
'Now turn off the autoredrawing for the Listview control
lvw.Visible = False
'OK, so far so good. Now iterate through all columns and set column width to the widest
For iCounter = 0 To lvw.ColumnHeaders.Count - 1
Call SendMessage(lvw.hWnd, LVM_SETCOLUMNWIDTH, iCounter, ByVal LVSCW_AUTOSIZE_USEHEADER)
'Now turn on the autoredrawing for the Listview control
lvw.Visible = True
Please email me suggestions, improvements or anything else you want to be included on my pages.