Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

removing the empty gray space in datagrid in c#

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

how do i remove the empty space i.e. i want the datagrid to automatically resize itself depending upon the no. of rows. i know for columns we can do that by using fill value in AutoSizeColumnMode, but there is no fill value for AutoSizeRowsMode.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It can be done, you'd have to adjust the ClientSize when a row is added or removed. However, it doesn't hide the background completely once the vertical scrollbar appears and the grid height is not a divisble by the row height. Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...