使用鼠标滚轮滚动DataGridView

6

我们都熟悉鼠标点击并按住鼠标按钮,然后将鼠标移动到网格的边缘,列/行滚动并且选择区域增加的功能。

我有一个基于DataGridView的控件,由于性能问题,我必须关闭MultiSelect并自己处理选择过程,现在点击+按住滚动功能也被禁用了。

有什么建议可以重新编写此功能吗?

我考虑使用简单的MouseLeave事件,但我不确定如何确定它离开的位置,并实现动态滚动速度。


你能具体说明一下你的问题吗?你可以提供一段代码吗(如果你已经写了什么的话)? - Priyank
我还没有做任何事情......在编写代码之前,我希望能得到一些(普遍的)指导,以便合理地解决问题。 - ChandlerPelhams
3个回答

11

只需将以下代码添加到您的Form1_Load

DataGridView1.MouseWheel += new MouseEventHandler(DataGridView1_MouseWheel);

这个是用于鼠标滚轮事件的。

void DataGridView1_MouseWheel(object sender, MouseEventArgs e)
{
    int currentIndex = this.DataGridView1.FirstDisplayedScrollingRowIndex;
    int scrollLines = SystemInformation.MouseWheelScrollLines;

    if (e.Delta > 0) 
    {
        this.DataGridView1.FirstDisplayedScrollingRowIndex 
            = Math.Max(0, currentIndex - scrollLines);
    }
    else if (e.Delta < 0)
    {
        this.DataGridView1.FirstDisplayedScrollingRowIndex 
            = currentIndex + scrollLines;
    }
}

1
有时候我会遇到“System.ArgumentOutOfRangeException”的错误。 - Timeless

4

完整答案 您需要设置焦点DataGridview

private void DataGridView1_MouseEnter(object sender, EventArgs e)
        {
            DataGridView1.Focus();
        }

then Add Mouse wheel event in Load function 
DataGridView1.MouseWheel += new MouseEventHandler(DataGridView1_MouseWheel);

Finally Create Mouse wheel function

void DataGridView1_MouseWheel(object sender, MouseEventArgs e)
{
    int currentIndex = this.DataGridView1.FirstDisplayedScrollingRowIndex;
    int scrollLines = SystemInformation.MouseWheelScrollLines;

    if (e.Delta > 0) 
    {
        this.DataGridView1.FirstDisplayedScrollingRowIndex = Math.Max(0, currentIndex - scrollLines);
    }
    else if (e.Delta < 0)
    {
        if (this.DataGridView1.Rows.Count > (currentIndex + scrollLines))
            this.DataGridView1.FirstDisplayedScrollingRowIndex = currentIndex + scrollLines;
    }
}

对我来说它很好用。


1
如果满足以下条件,System.ArgumentOutOfRangeException异常将不会发生:
void DataGridView1_MouseWheel(object sender, MouseEventArgs e)
{
    int currentIndex = this.DataGridView1.FirstDisplayedScrollingRowIndex;
    int scrollLines = SystemInformation.MouseWheelScrollLines;

    if (e.Delta > 0) 
    {
        this.DataGridView1.FirstDisplayedScrollingRowIndex = Math.Max(0, currentIndex - scrollLines);
    }
    else if (e.Delta < 0)
    {
        if (this.DataGridView1.Rows.Count > (currentIndex + scrollLines))
            this.DataGridView1.FirstDisplayedScrollingRowIndex = currentIndex + scrollLines;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接