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 set the width of a column in a DataGrid?

To set a column width, your DataGrid must be using a non-null DataGridTableStyle. Once this is in place, you can set the column width by first getting the tablestyle and then using that object to obtain a column style with which you can set the width. Here are some code snippets showing how you might do this.

Make sure your DataGrid is using a tablestyle:

dataGrid1.DataSource = dataSet.Tables[ "customers" ];
DataGridTableStyle dgts = new DataGridTableStyle();
dgts.MappingName = "customers";
dataGrid1.TableStyles.Add(dgts);

Method to set a column with by column number:

public void SetColWidth( DataGridTableStyle tableStyle, int colNum, int width )
{
  try
  {
    tableStyle.GridColumnStyles[ colNum ].Width = width;
    tableStyle.DataGrid.Refresh();
  }
  catch{} //empty catch .. do nothing
}

Here is how you might call this method:

private void button1_Click( object sender, EventArgs e )
{
  DataGridTableStyle tableStyle = dataGrid1.TableStyles[ "customers" ];
  SetColWidth( tableStyle, 1, 200 );
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter