How can I force the vertical scrollbar in my DataGrid to always be visible

Platform: WinForms| Category: Datagrid

Derive a DataGrid. In your derived grid, add a handler for the VertScrollBar.VisibleChanged event. In your handler, if the scrollbar is not visible, size it and position it, and then show it. The code below assumes no horizontal scrollbar is necessary. If it is present, you would have to adjust the sizing code.

C#
public class MyDataGrid : DataGrid
{

	public MyDataGrid()
	{
		//make scrollbar visible & hook up handler
		this.VertScrollBar.Visible = true;
		this.VertScrollBar.VisibleChanged += new EventHandler(ShowScrollBars);
	}

	private int CAPTIONHEIGHT = 21;
	private int BORDERWIDTH = 2;
	
	private void ShowScrollBars(object sender, EventArgs e)
	{
		if(!this.VertScrollBar.Visible)
		{
			int width = this.VertScrollBar.Width;
			this.VertScrollBar.Location = new Point(this.ClientRectangle.Width - width  - BORDERWIDTH, CAPTIONHEIGHT);
			this.VertScrollBar.Size = new Size(width, this.ClientRectangle.Height - CAPTIONHEIGHT - BORDERWIDTH);
			this.VertScrollBar.Show();				
		}
	}
}

VB.NET
Public Class MyDataGrid
	Inherits DataGrid
   
	Public Sub New()
		’make scrollbar visible & hook up handler
		Me.VertScrollBar.Visible = True
		AddHandler Me.VertScrollBar.VisibleChanged, AddressOf ShowScrollBars
	End Sub ’New
   
	Private CAPTIONHEIGHT As Integer = 21
	Private BORDERWIDTH As Integer = 2
   
	Private Sub ShowScrollBars(sender As Object, e As EventArgs)
		If Not Me.VertScrollBar.Visible Then
			Dim width As Integer = Me.VertScrollBar.Width
			Me.VertScrollBar.Location = New Point(Me.ClientRectangle.Width - width - BORDERWIDTH, CAPTIONHEIGHT)
			Me.VertScrollBar.Size = New Size(width, Me.ClientRectangle.Height - CAPTIONHEIGHT - BORDERWIDTH)
			Me.VertScrollBar.Show()
		End If
	End Sub ’ShowScrollBars
End Class ’MyDataGrid

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.