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 CustomDataGrid : DataGrid
{
public CustomDataGrid()
{
// make scrollbar visible & add handler
VertScrollBar.Visible = true;
VertScrollBar.VisibleChanged += new EventHandler( ShowScrollBars );
}
private const int CAPTIONHEIGHT = 21;
private const int BORDERWIDTH = 2;
private void ShowScrollBars( object sender, EventArgs e )
{
if ( !VertScrollBar.Visible )
{
int width = VertScrollBar.Width;
VertScrollBar.Location =
new Point( ClientRectangle.Width - width - BORDERWIDTH, CAPTIONHEIGHT );
VertScrollBar.Size =
new Size( width, ClientRectangle.Height - CAPTIONHEIGHT - BORDERWIDTH );
VertScrollBar.Show();
}
}
}
[Visual Basic]
Public Class CustomDataGrid
Inherits DataGrid
Public Sub New()
' make scrollbar visible & add handler
VertScrollBar.Visible = True
AddHandler VertScrollBar.VisibleChanged, AddressOf ShowScrollBars
End Sub
Private ReadOnly CAPTIONHEIGHT As Integer = 21
Private ReadOnly BORDERWIDTH As Integer = 2
Private Sub ShowScrollBars(ByVal sender As Object, ByVal e As EventArgs)
If Not VertScrollBar.Visible Then
Dim width As Integer = VertScrollBar.Width
VertScrollBar.Location = _
New Point(ClientRectangle.Width - width - BORDERWIDTH, CAPTIONHEIGHT)
VertScrollBar.Size = _
New Size(width, ClientRectangle.Height - CAPTIONHEIGHT - BORDERWIDTH)
VertScrollBar.Show()
End If
End Sub
End Class
Contributed from George Shepherd's Windows Forms FAQ