16

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Night Walker
  • 20,638
  • 52
  • 151
  • 228

5 Answers5

19

Yes, I think you are looking for the AutoSizeMode property.

int n = grid.Columns.Count;
grid.Columns[n].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

Edit: Try setting the width to "*" as seen below. You'll have to do this in the code if your columns are auto-generated.

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn Width="Auto" />
    <DataGridTextColumn Width="*" />
  </DataGrid.Columns>
</DataGrid>
user807566
  • 2,828
  • 3
  • 20
  • 27
6

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);
    }
Stuka
  • 71
  • 1
  • 2
0

Try this approach guys, I wrote it this morning, robust and reliable and allows for percentage based width columns taking all available space. https://stackoverflow.com/a/10526024/41211

Community
  • 1
  • 1
GONeale
  • 26,302
  • 21
  • 106
  • 149
0

DataGrid.Columns[x].Width = DataGridLength.Auto;

Goobakide
  • 9
  • 1
0

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); 
    }
}
hnnngwdlch
  • 2,761
  • 1
  • 13
  • 20