自動調整datagrid列寬(根據行、列長度比較自動調整寬度)

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace DataGridResize_CS
{
 /// <summary>
 /// Summary description for Form1.
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Windows.Forms.Label label1;
  /// <summary>
  /// Required designer variable.
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Required for Windows Form Designer support
   //
   InitializeComponent();

   //
   // TODO: Add any constructor code after InitializeComponent call
   //
  }

  /// <summary>
  /// Clean up any resources being used.
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {
   this.dataGrid1 = new System.Windows.Forms.DataGrid();
   this.label1 = new System.Windows.Forms.Label();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
   this.SuspendLayout();
   //
   // dataGrid1
   //
   this.dataGrid1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    | System.Windows.Forms.AnchorStyles.Left)
    | System.Windows.Forms.AnchorStyles.Right);
   this.dataGrid1.DataMember = "";
   this.dataGrid1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
   this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
   this.dataGrid1.Location = new System.Drawing.Point(16, 24);
   this.dataGrid1.Name = "dataGrid1";
   this.dataGrid1.Size = new System.Drawing.Size(304, 244);
   this.dataGrid1.TabIndex = 0;
   this.dataGrid1.SizeChanged += new System.EventHandler(this.dataGrid1_SizeChanged);
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(64, 8);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(224, 16);
   this.label1.TabIndex = 1;
   this.label1.Text = "Size the form to size the grid.";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 13);
   this.ClientSize = new System.Drawing.Size(336, 278);
   this.Controls.AddRange(new System.Windows.Forms.Control[] {
                    this.label1,
                    this.dataGrid1});
   this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
   this.Name = "Form1";
   this.Text = "Form1";
   this.Load += new System.EventHandler(this.Form1_Load);
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// The main entry point for the application.
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private int headerWidth; //width of row header
  private int nCols; //number of columns in teh datatable
  
  private void Form1_Load(object sender, System.EventArgs e)
  {
   //get a datatable somehow
   DataTable dt = new DataTable("MyTable");
   this.nCols = 4;
   int nRows = 7;
   for(int i = 0; i < nCols; i++)
    dt.Columns.Add(new DataColumn(string.Format("Col{0}", i)));
   for(int i = 0; i < nRows; ++i)
   {
    DataRow dr = dt.NewRow();
    for(int j = 0; j < nCols; j++)
     dr[j] = string.Format("rrrr{0} cccc{1}", i, j);
    dt.Rows.Add(dr);
   }

   //add a table style so the columnstyles can be accessed
   DataGridTableStyle ts = new DataGridTableStyle();
   ts.MappingName = "MyTable";
   this.dataGrid1.TableStyles.Add(ts);

   this.dataGrid1.DataSource = dt;

   //this.DataGrid1.RowHeadersVisible = false;

   //trick to know the header width of the row header
   this.headerWidth = this.dataGrid1.GetCellBounds(0, 0).X;

   //call to a routine that will equally size the columns in the client area
   SizeEqually(this.dataGrid1.TableStyles["MyTable"]);
  }

  //make columns equally occupy grid's client area
  private void SizeEqually(DataGridTableStyle ts)
  {
   
   if (ts == null)
    return;
       
   //get a reference to the GridColumnStyles
   GridColumnStylesCollection colStyles = ts.GridColumnStyles;

   //get the target width
   int width = this.dataGrid1.Size.Width - this.headerWidth - 4; // the 4 handles the borders
   if(IsScrollBarVisible(this.dataGrid1))
    width -= SystemInformation.VerticalScrollBarWidth;
       
   int lastColIndex  = this.nCols - 1;

   //set to zero so horizontal scroll does not show as your size
   //frees up room in case leading cols grid during resize and try to flash teh HScroll
   colStyles[lastColIndex].Width = 0;

   int colWidth = width / nCols;

   int rowWidth = 0;
   DataTable dt = (DataTable)this.dataGrid1.DataSource;
   Graphics g = Graphics.FromHwnd(dataGrid1.Handle);
   StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
 
   SizeF size = SizeF.Empty;
   for(int i = 0; i < lastColIndex; i++)
   {
    for(int n = 0; n < dt.Rows.Count; n++)
    {
     size = g.MeasureString(dataGrid1[n, i].ToString(), dataGrid1.Font, 500, sf);
     if (size.Width > rowWidth)
     {
      rowWidth = (int)size.Width;
     }
    }
    if (rowWidth > colWidth)
    {
     colStyles[i].Width = rowWidth;
    }
    else
    {
     colStyles[i].Width = colWidth;
    }
   }
       
   //make last col fit whatever is left (handles pixels lost to int division
   colStyles[lastColIndex].Width = width - (nCols - 1) * colWidth;
  }

  private void dataGrid1_SizeChanged(object sender, System.EventArgs e)
  {
   SizeEqually(this.dataGrid1.TableStyles["MyTable"]);
  }

   
  private bool IsScrollBarVisible(Control aControl)
  {
   foreach(Control c in aControl.Controls)
   {
    if (c.GetType().Equals(typeof(VScrollBar)))
    {
     return c.Visible;
    }
   }
   return false;
  }

  
 }
 
 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章