删除c#中datagrid中的空灰色空格

时间:2010-01-23 11:35:57

标签: c#

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

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

3 个答案:

答案 0 :(得分:11)

可以这样做,你必须在添加或删除行时调整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;
  }
}

答案 1 :(得分:9)

有点黑客但你可以试试这个:

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

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

答案 2 :(得分:3)

设置datagrid的MaxHeight属性。例如MaxHeight="150"

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