简体   繁体   中英

check if a scroll bar is visible in a datagridview

I would like to display something if the data grid View is long and showing a scroll bar but don't know how to check if the scroll bar is visible. I can't simply add the rows since some may be not visible. I can't use an event since my code is already in an event.

you can try this out:

foreach (var scroll in dataGridView1.Controls.OfType<VScrollBar>())
{
   //your checking here
   //specifically... if(scroll.Visible)
}

I prefer this one :

//modif is a modifier for the adjustment of the Client size of the DGV window
//getDGVWidth() is a custom method to get needed width of the DataGridView

int modif = 0;
if (DataGridView.Controls.OfType<VScrollBar>().First().Visible)
{
    modif = SystemInformation.VerticalScrollBarWidth;
}
this.ClientSize = new Size(getDGVWidth() + modif, [wantedSizeOfWindow]);

so the only Boolean condition you need is:

if (DataGridView.Controls.OfType<VScrollBar>().First().Visible)
{
    //want you want to do
}

The DataGridView 's Scrollbars Property can be questioned using the ScrollBars Enumeration by masking it with the one you are interested in like this:

if ((dataGridView1.ScrollBars & ScrollBars.Vertical) != ScrollBars.None) ...

Note, that the two 'ScrollBars' are different things here!

To determine if the vertical scrollbar is present, you need to check how tall your visible rows are and compare against the datagridview height.

if(dgv1.Height > dgv1.Rows.GetRowsHeight(DataGridViewElementStates.Visible))
{
    // Scrollbar not visible
}
else
{
    // Scrollbar visible
}

Though to be more exact you may need to include a check of column widths as the presence of a horizontal scrollbar could create a vertical scrollbar that otherwise isn't there.

The answer from terrybozzio works only if you use the System.Linq namespace. A solution without using System.Linq is shown below:

foreach (var Control in dataGridView1.Controls)
{
    if (Control.GetType() == typeof(VScrollBar))
    {
        //your checking here
        //specifically... if (((VScrollBar)Control).Visible)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM