Stretching columns to fill all available space of DataGrid

Viewed 28401

Is it possible to stretch columns or the last column to fill all the available space of the data grid?

<DataGrid Grid.Row="0" AutoGenerateColumns="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="dataGrid1"   ItemsSource="{Binding Customers}" />

My columns are Auto generated.

5 Answers

Since the vast majority of the answers I've found on this topic deal with XAML, here is a C# solution to set all columns to fill the available space in the datagrid.

    foreach (var column in this.datagrid.Columns)
    {
        column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }

If you want to set all column widths to auto except the last column, which should fill the remaining space, try the following code:

for (int i = 0; i < grid.Columns.Count; i++)
{
    if (i == grid.Columns.Count - 1)
    {
        grid.Columns[i].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }
    else
    {
        grid.Columns[i].Width = new DataGridLength(1, DataGridLengthUnitType.Auto); 
    }
}
Related