Scrolling a DataGridView with the Mouse

So, we are all familiar with the functionality of clicking and holding the mouse button, then move the mouse to the edge of the grid, scroll through the columns / rows and increase the selection.

I have a DataGridView-based control that I had to disable MultiSelect and handle the selection process myself due to performance issues, and now the click + hold scroll function is also disabled.

Any suggestions on how to start writing in this function?

I was thinking of using something as simple as the MouseLeave event, but I'm not sure how to determine which position he left, or to implement dynamic scroll speed.

+6
source share
3 answers

Just add this code to your Form1_Load

DataGridView1.MouseWheel += new MouseEventHandler(DataGridView1_MouseWheel); 

And this is for the MouseWheel event

 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; } } 
+7
source

Complete answer You need to install 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; } } 

This works great for me.

+2
source

A System.ArgumentOutOfRangeException exception will not occur if:

 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
source

Source: https://habr.com/ru/post/902038/


All Articles