我的 C# .NET 应用程序中的一个表单有多个 DataGridView,它们实现拖放以移动行。拖放大部分工作正常,但我一直很难将 DataGridView 设置为 AutoScroll - 当一行被拖动到框的顶部或底部附近时,将它朝那个方向滚动。
到目前为止,我已经尝试实现 this 的一个版本解决方案。我有一个继承自 DataGridView 的 ScrollingGridView 类,它实现了所描述的计时器,并且根据调试器,计时器正在适本地触发,但是计时器代码:
const int WM_VSCROLL = 277;
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private void ScrollingGridViewTimerTick(object sender, EventArgs e)
{
SendMessage(Handle, WM_VSCROLL, (IntPtr)scrollDirectionInt, IntPtr.Zero);
}
据我所知没有做任何事情,可能是因为我在表单中有多个 DataGridView。我还尝试修改 AutoScrollOffset 属性,但那也没有做任何事情。对 DataGridView 和 ScrollBar 类的调查似乎没有提出任何其他实际使 DataGridView 滚动的命令或函数。任何人都可以帮我提供一个实际滚动 DataGridView 的功能,或其他一些解决问题的方法吗?
最佳答案
private void TargetReasonGrid_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
//Converts window position to user control position (otherwise you can use MousePosition.Y)
int mousepos = PointToClient(Cursor.Position).Y;
//If the mouse is hovering over the bottom 5% of the grid
if (mousepos > (TargetReasonGrid.Location.Y + (TargetReasonGrid.Height * 0.95)))
{
//If the first row displayed isn't the last row in the grid
if (TargetReasonGrid.FirstDisplayedScrollingRowIndex < TargetReasonGrid.RowCount - 1)
{
//Increase the first row displayed index by 1 (scroll down 1 row)
TargetReasonGrid.FirstDisplayedScrollingRowIndex = TargetReasonGrid.FirstDisplayedScrollingRowIndex + 1;
}
}
//If the mouse is hovering over the top 5% of the grid
if (mousepos < (TargetReasonGrid.Location.Y + (TargetReasonGrid.Height * 0.05)))
{
//If the first row displayed isn't the first row in the grid
if (TargetReasonGrid.FirstDisplayedScrollingRowIndex > 0)
{
//Decrease the first row displayed index by 1 (scroll up 1 row)
TargetReasonGrid.FirstDisplayedScrollingRowIndex = TargetReasonGrid.FirstDisplayedScrollingRowIndex - 1;
}
}
}
这里有很多有用的答案,我只是想为这个问题添加一个不太复杂的解决方案。当在 DataGridView 中拖动行时调用上面的代码。我的命名为“TargetReasonGrid”。
我添加了注释来解释我在做什么,但这里是详细说明的步骤:
转换鼠标位置,使其相对于网格位置(在您的表单/控件内)
在显示的网格边缘设置假想区域,鼠标移动将触发滚动
检查以确保您确实有不同的行要滚动到
以 1 行为增量滚动
感谢 C4u(上面的评论),给了我“假想区域”的想法。
关于c# - 如何在拖放期间自动滚动 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2567809/