使用鼠标滚动DataGridView

时间:2011-11-21 19:00:24

标签: c# winforms datagridview

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

我有一个基于DataGridView的控件,由于性能问题,我不得不关闭MultiSelect并自行处理选择过程,现在点击+保持滚动功能也被禁用。

关于如何回复此功能的任何建议?

我正在考虑使用像MouseLeave事件这样简单的东西,但我不确定如何确定它留下的位置,以及实现动态滚动速度。

3 个答案:

答案 0 :(得分:8)

只需将此代码添加到 Form1_Load

即可
DataGridView1.MouseWheel += new MouseEventHandler(DataGridView1_MouseWheel);

这个是针对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 :(得分:2)

完整答案 您需要设置Focus 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;
    }
}

它适用于我。

答案 2 :(得分:1)

如果出现以下情况,则不会发生System.ArgumentOutOfRangeException:

ExecStart=/bin/bash -c "a='hello world'; echo $${a}"