Search code examples
c#wpfdatatabledatagrid

How to add columns to a DataGrid?


I'm basing myself on this other question to show a DataGrid with some columns (no rows to be populated yet, just the columns):

I have following source code:

cs file:

public partial class MainWindow : Window
{
    private DataTable dt_main;
    ...
}

private ...first_Click(object sender, ...)
{
    dt_main = new DataTable("dt_main"); // just a default name, no such table
    DataGrid1.DataContext = dt_main.DefaultView;
}

private ...second_Click(object sender, ...)
{
    dt_main.Columns.Clear();
    ...
    while (...)
      dt_main.Columns.Add(tmp_ColName);
}

XAML file:

<DataGrid x:Name="DataGrid1" ... AutoGenerateColumns="True" ItemsSource="{Binding}"/>

I click on the first_click (this is for filling the list of tables) and then on second_click (this is for choosing the table), but although the DataTable's Columns attribute is filled in, I see nothing in my DataGrid, as you can see in following screenshot (the DataGrid is shown by the red arrow):

screenshot

Does anybody know what I'm missing?


Solution

  • The columns are only auto-generated when the ItemsSource property is actually set.

    Either set it explicitly after you have added the columns to the DataTable or also add the columns to the DataGrid:

    private ...second_Click(object sender, ...)
    {
        //add the columns to dt_main...
    
        DataGrid1.ItemsSource = null;
        DataGrid1.ItemsSource = dt_main.DefaultView;
    }