检查DataGridView中是否可见滚动条

13

如果数据网格视图很长并且显示滚动条,我希望显示一些内容,但是不知道如何检查滚动条是否可见。我不能简单地添加行,因为有些行可能不可见。我不能使用事件,因为我的代码已经在事件中。


需要更多细节。你尝试了什么?你想要做什么? - Alezis
我正在滚动条旁边添加一个指示器,用于指示重要信息的位置,类似于Visual Studio。 - ZNackasha
1
我不确定你具体指的是什么。你尝试过这个吗:https://dev59.com/ek3Sa4cB1Zd3GeqPuFP6 或者只是检查滚动条的“Visible”属性? - Alezis
谢谢那个链接非常有帮助。我使用了dataGridView1.Controls.OfType<VScrollBar>().First().visible; - ZNackasha
5个回答

17

你可以尝试这个:

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

最终使用了这种方法来使得 datagridview 达到正确宽度,虽然这意味着需要将 datagridview 的宽度逐一增加,直到水平滚动条不再可见。http://stackoverflow.com/questions/37635932/calculate-padding-of-datagridview-when-padding-is-greater-than-two如果您知道更有效的方法,请告诉我。谢谢。 - barlop

10

我更喜欢这个:

//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]);

所以你唯一需要的布尔条件是:

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

1
不错的解决方案。我建议添加一个额外的检查,因为 First() 可能会抛出异常:var vScrollBar = dgvEntity.Controls.OfType<VScrollBar>().FirstOrDefault(); if (vScrollBar != null && vScrollBar.Visible) vScrollbarWidth = SystemInformation.VerticalScrollBarWidth; - jacktric

4

DataGridViewScrollbars 属性可以使用 ScrollBars 枚举来查询,通过与您感兴趣的枚举进行屏蔽即可。操作方法如下:

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

请注意,这里的两个“滚动条”是不同的东西!

这个程序创建了一个DataGridView,虽然那一行显示它有滚动条,但实际上它是没有的。http://pastebin.com/raw/vfu6j09T - barlop
抱歉,我不理解。 - TaW
我认为我是在说,在 pastebin 链接的代码中,即使 datagridview 没有滚动条,它始终显示那个 messagebox。 - barlop

3

terrybozzio的答案只对使用System.Linq命名空间的情况有效。 以下是一种不使用System.Linq的解决方案:

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

2

要确定垂直滚动条是否存在,您需要检查可见行的高度并将其与datagridview的高度进行比较。

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

更准确地说,您可能需要检查列宽度,因为水平滚动条的存在可能会创建一个本来不存在的垂直滚动条。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接