shreya shreya - 3 months ago 23
C# Question

How can I make DataGrid columns stretch as the control changes width?

Right now when i re-size my screen the data grid columns are getting cut. So please give me a solution to re-size my data grid columns when i re-size my window. How can i set a dynamic width to my data grid columns.

<DataGrid Name="dtGrid" >
<DataGrid.Columns >
<DataGridTextColumn Header="Name" Binding="{Binding custname}" Width="150" />
<DataGridTextColumn Header="Mobile NO" Binding="{Binding Mobileno}" Width="150" FontFamily="Times New Roman"/>
<DataGridTextColumn Header="Credit" Binding="{Binding credit}" Width="150" FontFamily="Times New Roman"/>
</DataGrid.Columns>
</DataGrid>

Answer

Instead of giving a hardcode Width to all your columns. You can mention STAR sizing for your columns, so that the columns will auto adjust based on the available size.

   <DataGrid Name="dtGrid">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"
                                Binding="{Binding custname}"
                                Width="*" />
            <DataGridTextColumn Header="Mobile NO"
                                Binding="{Binding Mobileno}"
                                Width="*"
                                FontFamily="Times New Roman" />
            <DataGridTextColumn Header="Credit"
                                Binding="{Binding credit}"
                                Width="*"
                                FontFamily="Times New Roman" />
        </DataGrid.Columns>
    </DataGrid>