如何以编程方式滚动winforms datagridview控件?

Isa*_*ger 11 scroll datagridview winforms

我在一个继承自datagridview的控件中实现了一些拖放功能.基本上我是从DGV中的某处拖动一行并将其放在其他地方,重新排序行.我遇到了一个问题.如果DGV太大而没有滚动条,那么当用户处于拖车中间时,如何让DGV向上或向下滚动?

我知道如何获取当前鼠标位置,并获得dgv矩形的位置等.所以,我可以很容易地发现我是在矩形的顶部还是下半部分...我只需要一种以编程方式滚动dgv的方法.如果我不必继续更改所选单元格来执行此操作,我更愿意.

有什么建议?

谢谢

艾萨克

Isa*_*ger 19

那么,既然这是一个DataGridView ...对不起,在问题"的WinForms" ......但我可以做到这一点..向上或向下滚动一行.

向上滑动:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex - 1
Run Code Online (Sandbox Code Playgroud)

向下滚动:

this.FirstDisplayedScrollingRowIndex = this.FirstDisplayedScrollingRowIndex + 1;
Run Code Online (Sandbox Code Playgroud)

你必须确保检查数字是否超出范围.


Bin*_*nil 11

你可以通过设置做到这一点HorizontalScrollingOffset/ VerticalScrollingOffsetDataGridView

设置Horizo​​ntalScrollingOffset

dataGridView1.HorizontalScrollingOffset = dataGridView1.HorizontalScrollingOffset + 10;
Run Code Online (Sandbox Code Playgroud)

校验

DataGridView.Horizo​​ntalScrollingOffset属性

因为VerticalScrollingOffset你可以使用反射

包含命名空间 System.Reflection

PropertyInfo verticalOffset = dataGridView1.GetType().GetProperty("VerticalOffset", BindingFlags.NonPublic | BindingFlags.Instance);
            verticalOffset.SetValue(this.dataGridView1, 10, null); 
Run Code Online (Sandbox Code Playgroud)

  • VerticalScrollingOffset具有只读属性..所以你只能"得到它",不能"设置"它. (2认同)

dea*_*ock 5

您可以通过向控件发送消息告诉它向上或向下滚动来使用WinAPI.

这是代码,我希望它有所帮助:

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);
Run Code Online (Sandbox Code Playgroud)

现在假设您的表单上有一个文本框控件.您可以移动它:

SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEUP,IntPtr.Zero); //ScrollUp
SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEDOWN,IntPtr.Zero); //ScrollDown
Run Code Online (Sandbox Code Playgroud)

如果那个经典的通用解决方案不适合你.您可能需要查看FirstDisplayedScrollingRowIndex属性,并在拖动过程中更改它与鼠标位置的关系.


Sal*_*lim 5

dgv.FirstDisplayedScrollingRowIndex = dgv.RowCount - 1;
Run Code Online (Sandbox Code Playgroud)