Sellorio
Sellorio

Reputation: 1960

Get Whether the user is scrolling a DataGridView or not

I'm looking to find out whether the user is currently holding down the vertical scroll bar or not.

This question spawns from the fact that scrolling is cancelled when a DataGridView's DataSource is updated.

What I'm hoping for is to make an extension method like IsUserScrolling() to put on the DataGridView. The idea is that I don't update the DataGridView until the user stops scrolling.

Upvotes: 3

Views: 1519

Answers (2)

King King
King King

Reputation: 63327

You can know if user scroll the DataGridView via Scroll event, you can know if user holding mouse down on the Thumb and scroll via its ScrollEventArgs like this:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  if(e.ScrollOrientation == ScrollOrientation.VerticalScroll &&
     (e.Type == ScrollEventType.LargeIncrement || e.Type == ScrollEventType.LargeDecrement)){
     //your code here
  }
}

The code above almost works well, however somehow you can change the VerticalScroll.Value (this doesn't exist) with Large Change programmatically, the event will be fired even when user doesn't hold mouse down on vertical thumb. So we can add condition MouseButtons == MouseButtons.Left to make it work better:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  if(e.ScrollOrientation == ScrollOrientation.VerticalScroll && MouseButtons == MouseButtons.Left &&
     (e.Type == ScrollEventType.LargeIncrement || e.Type == ScrollEventType.LargeDecrement)){
     //your code here
  }
}

Another short way to detect if user holding mouse down everywhere on the vertical scrollbar (both Thumb and Arrow Repeat button) using HitTest method, you can add more code to make it work more reliably so that we don't miss some kind of programmatical scroll with real user scrolling action:

private void dataGridView1_Scroll(object sender, ScrollEventArgs e){
  Point p = dataGridView1.PointToClient(MousePosition);
  if (dataGridView1.HitTest(p.X, p.Y).Type == DataGridViewHitTestType.VerticalScrollBar){
     //Your code here
  }
}

Upvotes: 2

No Idea For Name
No Idea For Name

Reputation: 11577

i've searched it and found an answer. it might not be the perfect answer, but it works:

i've created a dataGridView, and Created an hScrollBar, put the hScrollBar on top of the dataGridView scroll bar (you can use vScrollBar if you meant vertical), set the width of the scroll bar to be the same as the dataGridView, and on the Scroll event, i did:

  private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
  {
     dataGridView1.HorizontalScrollingOffset = hScrollBar1.Value;
  }

and this way you can use the MouseDown and MouseUp events of the hScrollBar. you well come

Upvotes: 0

Related Questions