【问题标题】:removing the empty gray space in datagrid in c#在c#中删除datagrid中的空白灰色空间
【发布时间】:2010-01-23 11:35:56
【问题描述】:

alt text http://www.freeimagehosting.net/uploads/260c1f6706.jpg

我如何删除空白空间,即我希望数据网格根据编号自动调整自身大小。的行。我知道对于列,我们可以通过在 AutoSizeColumnMode 中使用填充值来做到这一点,但 AutoSizeRowsMo​​de 没有填充值。

【问题讨论】:

  • 那是“认知障碍”的亮点。

标签: c#


【解决方案1】:

可以,添加或删除行时,您必须调整 ClientSize。但是,一旦出现垂直滚动条并且网格高度不能被行高整除,它就不会完全隐藏背景。向您的项目添加一个新类并粘贴如下所示的代码。编译。将新控件从工具箱顶部拖放到表单上。

using System;
using System.Drawing;
using System.Windows.Forms;

class AutoSizeGrid : DataGridView {
  private int gridHeight;
  private bool resizing;
  protected override void OnClientSizeChanged(EventArgs e) {
    if (!resizing) gridHeight = this.ClientSize.Height;
    base.OnClientSizeChanged(e);
  }
  protected override void OnRowsAdded(DataGridViewRowsAddedEventArgs e) {
    setGridHeight();
    base.OnRowsAdded(e);
  }
  protected override void OnRowsRemoved(DataGridViewRowsRemovedEventArgs e) {
    setGridHeight();
    base.OnRowsRemoved(e);
  }
  protected override void OnHandleCreated(EventArgs e) {
    this.BeginInvoke(new MethodInvoker(setGridHeight));
    base.OnHandleCreated(e);
  }
  private void setGridHeight() {
    if (this.DesignMode || this.RowCount > 99) return;
    int height = this.ColumnHeadersHeight + 2;
    if (this.HorizontalScrollBar.Visible) height += SystemInformation.HorizontalScrollBarHeight;
    for (int row = 0; row < this.RowCount; ++row) {
      height = Math.Min(gridHeight, height + this.Rows[row].Height);
      if (height >= gridHeight) break;
    }
    resizing = true;
    this.ClientSize = new Size(this.ClientSize.Width, height);
    resizing = false;
    if (height < gridHeight && this.RowCount > 0) this.FirstDisplayedScrollingRowIndex = 0;
  }
}

【讨论】:

  • 感谢您的努力,但我使用上面建议的方法摆脱了那个空间。
  • 我在测试中发现了一些问题,请看:prnt.sc/b3rf7g 我也可以删除小灰色行吗?根据数据,左手角有一个很大的区域:prnt.sc/b3rft4我该如何解决这个问题?
【解决方案2】:

有点小技巧,但你可以试试这个:

dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;

顺便说一句,这是reported as a bug

【讨论】:

  • 这行得通,但是你仍然有边框。知道如何删除它吗?
【解决方案3】:

设置数据网格的MaxHeight 属性。例如MaxHeight="150"

在我的情况下,我已经删除了您在上面的网格中用红色边框显示的空间。

【讨论】:

    猜你喜欢
    • 2013-08-15
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多