How to build A WPF Datagrid with an unknown number of columns

There is DataTable class in .Net. Its primary purpose is to communicate with relational database but it can be used nicely to store, display and edit tabular data (e.g. read and display .csv/Excel files -> DataTable + DataGrid in wpf, DataTable + DataGridView in WinForms).

DataTable columns (DataColumn) can be added/removed at runtime and DataGrid auto-generates columns (DataGridColumn) for them (enabled by default), using Name property for headers. Also DataTable supports sorting and filtering out-of-box.

note: DataGrid doesn’t clear Columns when new ItemsSource is assigned. So it is possible to have some predefined columns and use autogenerate as well.

note: DataGrid creates DataGridTextColumns by default. If more complex template is required, the process can be intercepted via AutoGeneratingColumn event (see example)

here is an example:

code

public class MyViewModel
{
    public DataTable Test { get; set; }
}

public MyWindow()
{
    InitializeComponent();
    var vm = new MyViewModel
                {
                    Test = new DataTable
                        {
                            Columns = {"A", "B", "C"}
                        }
                };            
    this.DataContext = vm;

}

xaml

<DataGrid AutoGenerateColumns="True"
          ItemsSource="{Binding Path=Test.DefaultView}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="#"/>
    </DataGrid.Columns>
</DataGrid>

the result (I entered some values)

datagrid

Leave a Comment