如何检测DataGridView控件中的垂直滚动条

在vs2008中使用winforms。 我有一个DataGridView,我想检测垂直滚动条何时可见。 我应该注册什么事件?

我在网格的最后一列中添加每个单元格值的求和,并在DataGridView底部的文本框中显示该值。

我希望这个文本框与单元格值保持一致(即使在滚动条存在之后,我已将它们对齐,因为它是$$值)。

压倒性的DGV行为通常是颈部的巨大痛苦。 尽管如此,这很快就到了。 在表单中添加一个新类并粘贴下面显示的代码。 编译。 将新控件从工具栏顶部拖放到表单上。 实现ScrollbarVisibleChanged事件。

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); } } 
 var vScrollbar = dataGridView1.Controls.OfType().First(); if (vScrollbar.Visible) { } 

您可以只遍历控件并注册一个事件处理程序,而不是使用Linq(Adam Butler),每次滚动条可见性更改时都会调用该事件处理程序。 我以这种方式实现它并且它运行得非常顺利:

 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; } 

在InitializeComponent()之后的某处执行此操作在处理程序中,执行您需要做的任何操作以响应垂直滚动条的可见性更改。 水平滚动条的工作方式相同(用HScrollBar替换VScrollBar):

 void c_VisibleChanged(object sender, EventArgs e) { VScrollBar vb = sender as VScrollBar; if (vb.Visible) _DataGridViewScrollbarWidth = vb.Width; else _DataGridViewScrollbarWidth = 0; } 

我认为没有事件……但你可以在网格可以增长的所有地方尝试这样的事情:

  • 获取gridview +标题中的实际行数
  • 将该数字乘以每行的高度
  • 如果结果大于DataGrid的高度,则必须有垂直滚动条。

自从他回答了问题后,我给了Hans Passant一个Check标记……然而,我又采取了另一条路线来解决问题。 由于对话框是模态的,因此项目列表将不会从创建时间更改。 因此,我可以调用下面的代码,以确保在对话框首次显示时文本框位于正确的位置。

  ///  /// Horizontally shifts the label and text boxes that display the total /// values so that the totals remain aligned with the columns. ///  private void ShiftTotalsDisplay(DataGridView grid, Label firstLabel, TextBox secondTextBox, TextBox thirdTextBox) { //Note if you have a rowheader add the width here also. int nameRightLoc = grid.Location.X + grid.Columns[0].Width; int fpRightLoc = nameRightLoc + grid.Columns[0].DividerWidth + grid.Columns[1].Width; int dlRightLoc = fpRightLoc + grid.Columns[1].DividerWidth + grid.Columns[2].Width; Point loc = firstLabel.Location; loc.X = nameRightLoc - firstLabel.Width - 2; firstLabel.Location = loc; loc = secondTextBox.Location; loc.X = fpRightLoc - secondTextBox.Width - 2; secondTextBox.Location = loc; loc = thirdTextBox.Location; loc.X = dlRightLoc - thirdTextBox.Width - 2; thirdTextBox.Location = loc; } 

如果你的dgv在面板内,那么你可以比较面板和dgv高度属性。 如果dgv比面板大,那么必须有一个滚动条,对吗?

喜欢 :

 int panel_height = pnl.Height; int dgv_height = (dgv.RowCount + 1) * 24; // You can play around with this 24 according to your cell styles if (dgv_height > panel_height) MessageBox.Show("Voila!"); 

将DGV最后一列的“AutoSizeMode”属性设置为“Fill”,并将TextBox的Width属性设置为等于dgv.Columns [“lastcolumn”]。宽度。