171 171 - 1 year ago 97
C# Question

Detecting when ListView scrollbar reaches the bottom in WinForms

How do I know when the WinForms ListView scrollbar reaches it's bottom ?
When this happens, I want the listview to be populated with more data (which is endless in theory in my case).

The OnScroll event gives me the scroll value from the top, but I have no way of knowing if the user can scroll any further or not.

171 171
Answer Source

I found an answer using some code from the great ObjectListView code-project: http://www.codeproject.com/KB/list/ObjectListView.aspx

call GetScrollInfo:

    private const int SIF_RANGE = 0x0001;
    private const int SIF_PAGE = 0x0002;
    private const int SIF_POS = 0x0004;
    private const int SIF_DISABLENOSCROLL = 0x0008;
    private const int SIF_TRACKPOS = 0x0010;
    private const int SIF_ALL = (SIF_RANGE | SIF_PAGE | SIF_POS | SIF_TRACKPOS);        
    private const int SB_HORZ = 0;
    private const int SB_VERT = 1;

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern bool GetScrollInfo(IntPtr hWnd, int fnBar, SCROLLINFO scrollInfo);

    public static SCROLLINFO GetFullScrollInfo(ListView lv, bool horizontalBar) {
      int fnBar = (horizontalBar ? SB_HORZ : SB_VERT);

      SCROLLINFO scrollInfo = new SCROLLINFO();
      scrollInfo.fMask = SIF_ALL;
      if (GetScrollInfo(lv.Handle, fnBar, scrollInfo))
        return scrollInfo;
        return null;

with this data struct:

    public class SCROLLINFO
        public int cbSize = Marshal.SizeOf(typeof(SCROLLINFO));
        public int fMask;
        public int nMin;
        public int nMax;
        public int nPage;
        public int nPos;
        public int nTrackPos;

the nMax gives the total max scroll value including the scroll handle itself, so the actually useful max value is nMax - nPage, where nPage is the size of the scroll handle.

This works great !