Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I automatically size a column in a DataGrid?

One way to do this is to use MeasureString to compute the size of the text in each cell, and then take the maximum value. Below is a code snippet that does this. It assumes your datagrid is bound to a datatable. You can download a full working sample. (C#,VB).

public void AutoSizeCol( int col )
{
  float width = 0;
  int numRows = ( (DataTable) dataGrid1.DataSource ).Rows.Count;

  using ( Graphics g = Graphics.FromHwnd( dataGrid1.Handle ) )
  {
    StringFormat sf = new StringFormat( StringFormat.GenericTypographic );
    for ( int i = 0; i < numRows; ++i )
    {
      SizeF size = g.MeasureString( dataGrid1[ i, col ].ToString(),
          dataGrid1.Font, 500, sf );
      if ( size.Width > width )
        width = size.Width;
    }
  }
  dataGrid1.TableStyles[ "customers" ].GridColumnStyles[ col ].Width =
      (int) width + 8; // 8 is for leading and trailing padding
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter