In a ListView control, with the View property set to Details, you can create a multi-column output. Sometimes you
will want the last column of the ListView to size itself to take up all remaining space. You can do this by
setting the column width to the magic value -2.
In the following example, the name of the ListView control is lvSample:
[c#]
private void Form1_Load(object sender, System.EventArgs e)
{
SizeLastColumn(lvSample);
}
private void listView1_Resize(object sender, System.EventArgs e)
{
SizeLastColumn((ListView) sender);
}
private void SizeLastColumn(ListView lv)
{
lv.Columns[lv.Columns.Count - 1].Width = -2;
}
[vb]
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
SizeLastColumn(lvSample)
End Sub
Private Sub ListView1_Resize(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles lvSample.Resize
SizeLastColumn(CType(sender, ListView))
End Sub
Private Sub SizeLastColumn(ByVal lv As ListView)
lv.Columns(lv.Columns.Count - 1).Width = -2
End Sub
You can also size a column to its contents. This is especially useful after adding an item to the
ListView. For example:
[c#]
lvSample.Items.Add("foo");
lvSample.Columns[0].Width = -1;
[vb]
lvSample.Items.Add("foo")
lvSample.Columns(0).Width = -1
If the column width is set to -1, the column is sized to the width of the widest item in it. If the value is set to -2, it
has a minimum width of the size of the column header, except for the last column, which takes up all remaining space.
|