itpov.com

An Information Technology point of view

AutoResize Listview Columns to both Header and Content

This post has been revived from the archives by request.

I use Listviews a lot in my programming, and one issue I have had is that the autoresize is for either the header or the content, but not both. So, I finally created a function I add to fit whichever of the two is the widest.
Private Sub BestFit(ByRef lvw As ListView)
        Dim lvCol As ColumnHeader
        ‘ loop through the columns
        For Each lvCol In lvw.Columns
            ‘ set the width to the column width
            lvCol.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
            ‘ record the width
            Dim width As Integer = lvCol.Width
            ‘ set the width to the header width
            lvCol.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
            ‘ if the original width is greater than the new width, revert to it
            If width > lvCol.Width Then
                lvCol.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
            End If
        Next
End Sub

November 28th, 2006 Posted by josh | Programming | one comment

1 Comment

  1. I’d probably recommend suspending the layout of the list view control so you don’t see the column resize twice, then after resume it to refresh the control.

    Comment by DanStory | November 29, 2006

Sorry, the comment form is closed at this time.