Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Autosize listview 1

Status
Not open for further replies.

TysonLPrice

Programmer
Jan 8, 2003
859
US
I'd like to autosize listview columns to fit the column names. From what I saw this should do it but it doesn't work for me. Can someone see what I'm doing wrong or know of a way to do it? The listview is designed to dynamically build the coulmns based on the number of coumns in a recordset.

Code:
For i As Integer = 0 To lvControl.Items.Count - 1
        lvControl.Columns(i).Width = -2
 Next i
 
This works nicely:

Code:
'API Declaration in General Declarations
   Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As IntPtr, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32

'API Constants
    Const SET_COLUMN_WIDTH As Long = 4126
    Const AUTOSIZE_USEHEADER As Long = -2

'Sub To Resize
    Private Sub AppNewAutosizeColumns(ByVal TargetListView As ListView)

        Const SET_COLUMN_WIDTH As Long = 4126
        Const AUTOSIZE_USEHEADER As Long = -2

        Dim lngColumn As Long

        For lngColumn = 0 To (TargetListView.Columns.Count - 1)

            Call SendMessage(TargetListView.Handle, _
                SET_COLUMN_WIDTH, _
                lngColumn, _
                AUTOSIZE_USEHEADER)

        Next lngColumn

    End Sub

'The Call
 AppNewAutosizeColumns(ListView1)
 
It really is suggested that you not use an API unless necessary.

Try:
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each ch As ColumnHeader In ListView1.Columns
            ch.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
        Next
    End Sub
If you want to adjust directly you can use ch.width instead.

-I hate Microsoft!
-Forever and always forward.
-My kingdom for a edit button!
 
I guess I should also say how you can fix your original code.
Code:
        For i As Integer = 0 To ListView1.[red]Columns[/red].Count - 1
            ListView1.Columns(i).Width = -2
        Next
You almost had it, but you did it off item count rather than column count.

-I hate Microsoft!
-Forever and always forward.
-My kingdom for a edit button!
 
Yes that is what I used...Someone here at work pointed out the error of my ways. Thanks for the response :)
 
np. :)

-I hate Microsoft!
-Forever and always forward.
-My kingdom for a edit button!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top