I am implementing a custom control which derives from ListView.
I would like for the final column to fill the remaining space (Quite a common task), I have gone about this via overriding the OnResize method:
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (Columns.Count == 0)
return;
Columns[Columns.Count - 1].Width = -2; // -2 = Fill remaining space
}
or via another method:
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (!_autoFillLastColumn)
return;
if (Columns.Count == 0)
return;
int TotalWidth = 0;
int i = 0;
for (; i < Columns.Count - 1; i++)
{
TotalWidth += Columns[i].Width;
}
Columns[i].Width = this.DisplayRectangle.Width - TotalWidth;
}
Edit:
This works fine until I dock the ListView into a parent container and resize via that control. Every second time the control size shrinks (IE, drag the the border one pixel), I get a scroll bar on the bottom which can't move at all (not even one pixel).
The result of which is when I drag the size of the parent I am left with a flickering scroll bar in the ListView, and a 50% chance it will be there when the dragging stops.
Try using the
ClientSize
property. As MSDN puts it:Edit: I've added a code sample demonstrating how achieve different fill behaviors.
When a form containing a listview is restored to FormWindowState.Normal from a maximized state, horizontal scroll bar is displayed even though column widths have been correctly adjusted. This happens when the resized column width shrinks but not when it grows. Here's a hack that can correct this without resorting to win32 calls. (magic number [-2] is just a simple shortcut)