Tuesday, April 21, 2009

C# - A custom DataGridView class with always vertical scroll bar visible

Depend on the data which you want to show in a DataGridView, sometimes you need to keep vertical scroll bars always visible. If you don't have enough row to fill the DataGridView vertically, and you aligned and configured the columns' width for situations which data show with vertical scroll bar, then it's better to show the bar always.

The only thing which you need to do the job, is to set the VerticalScrollBar.Visible property to "true" in VisibleChanged event. I added dgvSetVerticalBar to fix the position of scroll bar, and it's necessary to call it in Load event of form which contains this custom DataGridView.


using System;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;

namespace myNameSpace
{
public partial class myCustomDGV : DataGridView
{
public myCustomDGV()
{
// InitializeComponent();
this.VerticalScrollBar.Visible = true;
this.VerticalScrollBar.VisibleChanged +=
new EventHandler(VerticalScrollBar_VisibleChanged);

this.AllowUserToOrderColumns = false;
this.AllowUserToResizeColumns = false;
this.AllowUserToResizeRows = false;
this.RowHeadersVisible = false;
}

void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
{
this.VerticalScrollBar.Visible = true;
}

public void dgvSetVerticalBar()
{
this.VerticalScrollBar.SetBounds(
this.Width - this.VerticalScrollBar.Width - 1,
this.VerticalScrollBar.Location.Y + 1,
this.VerticalScrollBar.Width,
this.Height - 2);
}

}
}

Share/Bookmark

2 comments:

Unknown said...

Hi, im new to C#.
I dont understand how i can use this, could you please make an example?
Thank you very much.

Anonymous said...

Create custom scrolling bar for DataGridView