Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect the vertical scrollbar in a DataGridView control

Tags:

c#

.net

winforms

Using winforms in vs2008. I have a DataGridView and I would like to detect when the vertical scroll bar is visible. What event should I register for?

I am adding the summing the each cell value in the last column of the grid and displaying that value in a textbox at the bottom of the DataGridView.

I would like this textbox to stay lined up with the cell values (I have made them right aligned since it is $$ values) even after the scroll bar is present.

like image 719
Billy Avatar asked Apr 21 '10 18:04

Billy


4 Answers

var vScrollbar = dataGridView1.Controls.OfType<VScrollBar>().First();
if (vScrollbar.Visible)
{
}
like image 66
Adam Butler Avatar answered Nov 04 '22 17:11

Adam Butler


Overriding DGV behavior is usually a huge pain in the neck. Got this going pretty quickly though. Add a new class to your form and paste the code shown below. Compile. Drop the new control from the top of the toolbar onto a form. Implement the ScrollbarVisibleChanged event.

using System;
using System.Windows.Forms;

class MyDgv : DataGridView {
    public event EventHandler ScrollbarVisibleChanged;
    public MyDgv() {
        this.VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged);
    }
    public bool VerticalScrollbarVisible {
        get { return VerticalScrollBar.Visible; }
    }
    private void VerticalScrollBar_VisibleChanged(object sender, EventArgs e) {
        EventHandler handler = ScrollbarVisibleChanged;
        if (handler != null) handler(this, e);
    } 
}
like image 32
Hans Passant Avatar answered Nov 04 '22 19:11

Hans Passant


Set the DGV last column's "AutoSizeMode" property to "Fill" and set the TextBox's Width property equal to dgv.Columns["lastcolumn"].Width.

like image 1
Mansoor Ul Haq Avatar answered Nov 04 '22 19:11

Mansoor Ul Haq


Instead of using Linq (Adam Butler) you can just iterate through the controls and sign up an event handler that will be called each time the scrollbar visibility changes. I implemented it that way and it works pretty smoothly:

private System.Windows.Forms.DataGridView dgCounterValues;
private Int32 _DataGridViewScrollbarWidth;

// get vertical scrollbar visibility handler
foreach (Control c in dgCounterValues.Controls)
if (c.GetType().ToString().Contains("VScrollBar"))
{
    c.VisibleChanged += c_VisibleChanged;
}

do this somewhere after the InitializeComponent() In the handler, do whatever you need to do in response to the visibility change of the vertical scrollbar. Same works for the horizontal scrollbar (replace VScrollBar with HScrollBar):

void c_VisibleChanged(object sender, EventArgs e)
{
    VScrollBar vb = sender as VScrollBar;
    if (vb.Visible) _DataGridViewScrollbarWidth = vb.Width;
    else _DataGridViewScrollbarWidth = 0;
} 
like image 1
Andy3D Avatar answered Nov 04 '22 18:11

Andy3D