Fixed Width Columns in ListView

I like .NET's ListView control and I often end up using it in places where even ListBox would suffice. ListView with single column in Details view is exactly look that I usually shoot for.

Of course, width of column needs to be adjusted in order to maximize usable space. This is easily done by simply resizing column to fit width of ListView but with some space reserved for vertical scrollbar. Here is code for e.g. Form_Load:

listView_columnTest.Width = listView.ClientRectangle.Width - SystemInformation.VerticalScrollBarWidth;

And, if there weren't any users, that would be enough. Problem is that any user can change with of column and thus disturb our delicate balance :). Solution is in handling ListView.ColumnWidthChanging event. Somebody would expect that setting e.Cancel to true would be enough but this is actually not a case. Full solution requires two lines:

private void lsvFilters_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) {
e.NewWidth = ((ListView)sender).Columns[e.ColumnIndex].Width;
e.Cancel = true;
}

Leave a Reply

Your email address will not be published. Required fields are marked *