Programatically set the width of a DataColumn for use with a DataGrid

patrick picture patrick · Sep 20, 2010 · Viewed 13.8k times · Source

I assign a column programmatically to a DataTable like this:

myDataTable.Columns.Add(myDataColumn);

Is there a way to programmatically set the width / size of the column? I'm using WPF with C# in vs2010.

Answer

Scott picture Scott · Sep 20, 2010
ColumnDefinition col1 = new ColumnDefinition();
col1.Width = GridLength.Auto;
ColumnDefinition col2 = new ColumnDefinition();
col2.Width = new GridLength(1,GridUnitType.Star);

grid.ColumnDefinitions.Add(col1);
grid.ColumnDefinitions.Add(col2);

top pieces will auto size columns, bottom piece you can customize size. look into this site for more detail -- http://www.wpftutorial.net/GridLayout.html