Luke
Luke

Reputation: 18993

How can I make a ListView's columns auto-resize programmatically?

I've found some examples using the Win32 api or simulating the ^+ button combination (ctrl-+) using SendKeys, but at least with the SendKeys method the listview grabs the cursor and sets it to an hourglass until I hit the start button on my keyboard. What is the cleanest way to do this?

Upvotes: 5

Views: 34877

Answers (4)

Chris Raisin
Chris Raisin

Reputation: 442

After adding the following routine to your code then call it from any procedure/function. Do not use it in your "Form_Load" procedure though. Only call it after you have added an item to your ListView (or if you are making multiple additions, call it once at the end of all the additions):

    Private Sub AutoSizeListViewColumns(oListView As ListView)
        Dim nCol As Integer = 0
        SuspendLayout()
        For nCol = 0 To (oListView.Columns.Count - 1)
            oListView.Columns(nCol).Width = -1  'forces autosizing on column
        Next
        oListView.Refresh()
        ResumeLayout()
    End Sub

Upvotes: 0

Matt Nelson
Matt Nelson

Reputation: 991

Looks like a call to myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent) will do what you want. I would think, just call it after adding an item.

More info here

Upvotes: 20

RonB
RonB

Reputation: 145

loop through all columns and set width to -1 after adding content.

Upvotes: 0

rpetrich
rpetrich

Reputation: 32346

According to MSDN, if you set the column width to -1 then it will autosize to the widest item

Upvotes: 1

Related Questions