Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datagridview - prevent columns scrolling to right when changing rows

Status
Not open for further replies.

Yorkshireman2

Programmer
Jan 21, 2005
154
CA
Suppose you have clicked on column 1 or higher and that column is only partly displayed so some is hidden off to the right.
Now when you use the up/down arrows to change rows, that column scrolls/shifts over to the right to display it's right hand side.
This is not very pleasing and is also a nuisance if you have a primary key on the left column and wish to see this whenever changing rows.

The following code resets the row to show first column when you select a different row by arrow keys or clicking with the mouse.

Code:
Private Sub DataGridView1_RowLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
     DataGridView1.CurrentCell = DataGridView1.CurrentRow.Cells(0)
End Sub

Private Sub DataGridView1_RowEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowEnter
      DataGridView1.FirstDisplayedScrollingColumnIndex = 0
End Sub

Scrolling vertically with the wheel mouse or scroll bar still leaves the horizontal scroll position where you put it; it's only when you select a different row that the columns shift to show the first column again.

Basically you need to set the current cell to cell 0 as you leave the row then set the first displayed column to column 0 as you enter the new row.
Both steps are required to prevent problems and prevent continuous visual disturbances with every row change (which occur if you let the column change and paint then simply change column again in the row enter)

This method gives a pleasing, smooth change with subsequent row changes.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top