自动调整datagrid列宽(根据行、列长度比较自动调整宽度)

原创 2006年05月24日 22:08:00

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

  
 }
 
 
}

DBGrid 根据表格中数据长度自动调整表格宽度

在“自动设置表格宽度”文本框中获取每个字段实际使用的最大字节数,然后设置DBGrid表格列的Field.DisplayWidth属性来根据实际字段长度自动调整表格宽度,主要代码如下: procedur...

绑定adodc的datagrid自动调整列宽

  • 2014年10月06日 17:10
  • 1KB
  • 下载

DataGridView列的宽度、行的高度自动调整

DataGridView列的宽度、行的高度自动调整 标签: headerc#.net优化 2010-11-10 14:39 11283人阅读 评论(2) 收藏 举报  分类:   .NET开...

Delphi中实现DBGrid列宽度自动调整

      发现一些ERP的软件的查询,查询出来结果之后,有的字段列宽过大,这时候要通过右键--初始化表格设置 这样的方式来调整表格的列宽。这样操作让人觉得麻烦,突然在网上看到这样的一篇文章,记下来备...

easyui datagrid 列的内容超出所定义的列宽时,自动换行

定义表单  nowrap:false 例如: $(function() { $('#dg').datagrid({ title : "视频信息列表", url : "Vi...

easyui datagrid 列的内容超出所定义的列宽时,自动换行

定义表单  nowrap="false" pagination : true, // 当true时在DataGrid底部显示一个分页工具栏。默认false  rownumbers : tr...
  • china165
  • china165
  • 2015年02月03日 09:23
  • 12590

DataGrid当列宽超出当前宽度时,没有数据也恒有滚动条

附件是DataGrid支持滚动条的文件。 具体使用如下: 1)DataGrid使用控件模板 Setter Property="Template" Value="{DynamicResource grd...

解决表格自动换行问题:让表格宽度根据内容长度自动伸展

这是css的一个基础问题,只需要一个css样式即可解决。 使用 white-space:nowrap样式之后的页面效果如下: 详细代码如下: Title ...
  • a2ed23
  • a2ed23
  • 2017年01月13日 17:12
  • 406

DataGrid自动调整行高

这是Alex Harui写的一个关于自定义的基于流式的renderer使用演示。                       首先,它在左上角画了一个正方形,然后设置显示文本在右侧。每一行的文本值都...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:自动调整datagrid列宽(根据行、列长度比较自动调整宽度)
举报原因:
原因补充:

(最多只允许输入30个字)