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.
var vScrollbar = dataGridView1.Controls.OfType<VScrollBar>().First();
if (vScrollbar.Visible)
{
}
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);
}
}
Set the DGV last column's "AutoSizeMode" property to "Fill" and set the TextBox's Width property equal to dgv.Columns["lastcolumn"].Width.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With