2011-11-21 103 views
6

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

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

有关如何回写此功能的任何建议?

我想使用一些简单的MouseLeave事件,但我不知道如何确定它离开的位置,以及实现动态滚动速度。

+0

你能对你的问题更具体吗?你可以把一段代码(如果你做了什么)? – Priyank

+0

我还没有做任何事情......我希望能够在编码之前以合理的方式得到一些(一般)指导。 – ChandlerPelhams

回答

7

就在这个代码添加到您的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; 
    } 
} 
+0

有时我得到这个System.ArgumentOutOfRangeException – Timeless

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; 
    } 
} 
2

完整答案 你需要设置焦点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; 
    } 
} 

它适用于我。