Thursday, September 24, 2009

Sizing a ListView to Avoid Scrolling

I prefer to avoid horizontal scrollbars if possible. A horizontal scrollbar automatically appears in a ListView ActiveX control if the columns are sized too wide for the width of the ListView. I like to size the columns so they exactly fit within the width of the ListView. However, if the ListView’s Anchor property is set to resize the control when the user resizes the form, at some point a vertical scrollbar appears if the ListView is sized too short for the rows displayed. Since the scrollbar takes up some of the width of the ListView, a horizontal scrollbar also appears.

The trick is to detect when the vertical scrollbar appears and adjust the width of the columns so they fit within the remaining width. The following code, which goes in the Resize event of the form or container the ListView is in, handles that. This code assumes there’s only two columns and the second column should be resized. Adjust the code as necessary to use different columns

with This.oListView

* See if the ListView has a vertical scrollbar.

#define WS_HSCROLL 0x100000
#define WS_VSCROLL 0x200000
#define GWL_STYLE -16
declare integer GetWindowLong in Win32API integer hwnd, integer nIndex
llScroll = bitand(GetWindowLong(.hWnd, GWL_STYLE), WS_VSCROLL) <> 0

* Set the width of the second column.

lnWidth = .Width - .ColumnHeaders.Item(1).Width - sysmetric(4) - ;
iif(llScroll, sysmetric(7), 0) + 4
&& 4 is a fudge factor for width
.ColumnHeaders.Item(2).Width = max(lnWidth, 0)
endwith

No comments: