I have posted a function to auto-fit the columns in a ListView before. However, when I wanted to do the same thing for a DataGridView, the task is a little different (yet easier):
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
This blog is a depository for things I have found regarding VB.NET and C#.NET development (and other things I may need to remember). This blog is primarily for my own reference, but if the information I found is useful to others, then that is great. If others want to contribute with comments or other information, then that is great too.
Showing posts with label fit. Show all posts
Showing posts with label fit. Show all posts
Sunday, October 19, 2008
Sunday, June 17, 2007
How to Fit all columns in a ListView in C#, VB.NET, and VB6
Code is shown below to Autofit the data in a listview for C#, VB.NET, and VB6:
C#
VB.NET
VB6
Unfortunately, the VB6 solution is a bit more complicated:
You can change the LVSCW_AUTOSIZE_USEHEADER to LVSCW_AUTOSIZE if you do not want to consider the Header when adjusting the size.
More examples of the VB6 approach can be found at:
http://vbnet.mvps.org/index.html?code/comctl/lvcolumnautosize.htm
C#
public void AutoFitListView(ListView lv)
{
for (int i = 0; i <= lv.Columns.Count - 1; i++) { lv.Columns[i].Width = -2; // longest col head and item // -1 for just longest item } }
VB.NET
Public Sub AutoFitListView(ByRef lv As ListView)
For i As Integer = 0 To lv.Columns.Count - 1
lv.Columns(i).Width = -2
Next
End Sub
VB6
Unfortunately, the VB6 solution is a bit more complicated:
Private Const LVM_FIRST As Long = &H1000
Private Const LVM_SETCOLUMNWIDTH As Long = (LVM_FIRST + 30)
Private Const LVSCW_AUTOSIZE As Long = -1
Private Const LVSCW_AUTOSIZE_USEHEADER As Long = -2
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
Public Sub AutoFitListView(lv As ListView)
Dim i As Long
For i = 0 To lv.ColumnHeaders.count - 1
Call SendMessage(lv.hwnd, LVM_SETCOLUMNWIDTH, i, ByVal LVSCW_AUTOSIZE_USEHEADER)
Next
End Sub
You can change the LVSCW_AUTOSIZE_USEHEADER to LVSCW_AUTOSIZE if you do not want to consider the Header when adjusting the size.
More examples of the VB6 approach can be found at:
http://vbnet.mvps.org/index.html?code/comctl/lvcolumnautosize.htm
Subscribe to:
Posts (Atom)