Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WPF DataGrid.ItemsSource generates new Columns

I use a DataTable as source for my DataGrid:

  dt.Columns.Add("Update?", typeof(Boolean));
  dt.Columns.Add("Emulator", typeof(String));
  dt.Columns.Add("Path", typeof(String));

  ...      

  dataGrid1.ItemsSource = dt.DefaultView;

The XAML code to the DataGrid:

     <DataGrid  AutoGenerateColumns="True" Height="133" HorizontalAlignment="Left" Margin="0,81,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="688"  >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn CanUserResize="False" Header="Update?" />
            <DataGridTextColumn CanUserResize="False" Header="Emulator" IsReadOnly="False"/>
            <DataGridTextColumn CanUserResize="False" Header="Path" IsReadOnly="False"/>
        </DataGrid.Columns>
    </DataGrid>

So if the DataTable is empty I got an empty DataGrid showing the three headers names.
If the DataTable contains items the DataGrid gets extra columns instead of filling the already existing ones.

enter image description here

What can I do that the DataGrid fills up its existing columns?

like image 633
Gernot Lepej Avatar asked Feb 14 '23 08:02

Gernot Lepej


1 Answers

set AutoGenerateColumns="False"

if you set this property as true the columns will be created automatically

And also you need to set the binding , sample code :

<DataGrid Name="DG1" AutoGenerateColumns="False" ItemsSource="{Binding}">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Online Order?" IsThreeState="True" Binding="{Binding OnlineOrderFlag}" />
    </DataGrid.Columns>
</DataGrid>
like image 156
Damith Avatar answered Feb 19 '23 20:02

Damith