So we are all familiar with the functionality of click and holding down the mouse button, then moving the mouse to the edge of a grid, and the columns/rows scroll and the selection grows.
I have a DataGridView-based control that I had to turn MultiSelect off and handle the selection process myself due to performance issues, and now the click+hold scrolling feature is disabled as well.
Any suggestions about how to go about writing back in this functionality?
I was thinking of using something simple like the MouseLeave event, but I'm not sure how to determine which position it left, as well as implementing a dynamic scroll speed.
Just add this code to your Form1_Load
DataGridView1.MouseWheel += new MouseEventHandler(DataGridView1_MouseWheel);
And this one 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;
}
}
Complete Answer You need to set 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;
}
}
It works fine for me.
The System.ArgumentOutOfRangeException 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With