How do I programmatically scroll a winforms datagridview control?

前端 未结 5 1754
旧时难觅i
旧时难觅i 2020-12-03 17:44

I\'m implementing some drag drop features in one my controls inheriting from a datagridview. Basically I\'m dragging a row from somewhere in the DGV and dropping it somewher

5条回答
  •  有刺的猬
    2020-12-03 18:28

    You may do that using WinAPI by sending message to the control telling it to scroll up or down.

    Here is the code, I hope it helps:

    private const int WM_SCROLL = 276; // Horizontal scroll
    private const int WM_VSCROLL = 277; // Vertical scroll
    private const int SB_LINEUP = 0; // Scrolls one line up
    private const int SB_LINELEFT = 0;// Scrolls one cell left
    private const int SB_LINEDOWN = 1; // Scrolls one line down
    private const int SB_LINERIGHT = 1;// Scrolls one cell right
    private const int SB_PAGEUP = 2; // Scrolls one page up
    private const int SB_PAGELEFT = 2;// Scrolls one page left
    private const int SB_PAGEDOWN = 3; // Scrolls one page down
    private const int SB_PAGERIGTH = 3; // Scrolls one page right
    private const int SB_PAGETOP = 6; // Scrolls to the upper left
    private const int SB_LEFT = 6; // Scrolls to the left
    private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right
    private const int SB_RIGHT = 7; // Scrolls to the right
    private const int SB_ENDSCROLL = 8; // Ends scroll
    
    [DllImport("user32.dll",CharSet=CharSet.Auto)]
    private static extern int SendMessage(IntPtr hWnd, int wMsg,IntPtr wParam, IntPtr lParam);
    

    Now assuming you have a textbox control on your form. You can move it with:

    SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEUP,IntPtr.Zero); //ScrollUp
    SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEDOWN,IntPtr.Zero); //ScrollDown
    

    If that classic general solution doesn't work for you. You may want to look at FirstDisplayedScrollingRowIndex Property and change it regarding your mouse position during dragging.

提交回复
热议问题