Prevent WPF 4.0 Datagrid from Showing Empty Column

13,217

Solution 1

As vorrtex said in a comment the best thing to do is probably to set the column width to fill all available space:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTextColumn Header="FishLine ID" Width="*"/>
    </DataGrid.Columns>
    ...
</DataGrid>

Depending on the container you use you could also align the grid to the left side, leaving empty space to its right:

<DataGrid HorizontalAlignment="Left">
    <DataGrid.Columns>
        <DataGridTextColumn Header="FishLine ID"/>
    </DataGrid.Columns>
    ...
</DataGrid>

Hopefully that is what you were looking for...

Solution 2

I think you need to set AutoGenerateColumns to False, and do something like this:

<DataGrid AutoGenerateColumns = "False" ItemsSource = "{Binding BindSource}">
    <DataGrid.Columns>
        <DataGridTextColumn Header = "FishLine ID" Binding = "{Binding ID}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

That should do it :p

Solution 3

If width of one column is "*" even then I've seen empty column at right of datagrid. To solve this, specify the Width of datagrid as "Width=500" instead of MinWidth and MaxWidth.

<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="500" MinHeight="180" CanUserAddRows="False" CanUserDeleteRows="false" ItemsSource="{Binding MyList}" SelectedItem="{Binding SelectedValue}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Start Date" Binding="{Binding StartDate}" IsReadOnly="True" MinWidth="60" Width="Auto"/>
        <DataGridTextColumn Header="End Date" Binding="{Binding EndDate}" IsReadOnly="True" MinWidth="60" Width="*"/>
    </DataGrid.Columns>
</DataGrid>
Share:
13,217
Kiang Teng
Author by

Kiang Teng

Updated on July 06, 2022

Comments

  • Kiang Teng
    Kiang Teng almost 2 years

    alt text

    I have an application with a datagrid with 1 column (for now). How do I remove the second, empty column from the datagrid such that only columns with data are displayed in the datagrid.

  • Eido95
    Eido95 over 8 years
    Your answer didn't worked for me, instead I used the following DataGrid property definition, which worked for me: RowHeaderWidth="0"