Search code examples
c#wpfmvvmdata-bindingdatagrid

How to show selected columns from a datagrid that is bound to a list of objects?


I have a datagrid to display a dataset that i grab from an API service. Currently, the datagrid display the entire dataset. However, i only wish to display selected columns. Setting AutoGenerateColumns="False" option and than add in the columns to display give the following error "System.InvalidOperationException: 'Items collection must be empty before using ItemsSource.'" due to the collection should not exist yet before i run the program. I do not wish to hide or delete columns from the dataset as well. What method do i use to display those desired columns.

XAML

<DataGrid ItemsSource="{Binding Dataset}" AutoGenerateColumns="False" >
                        <DataGridTextColumn Header="A"
                          Binding="{Binding a}"/>
                        <DataGridTextColumn Header="B"
                          Binding="{Binding b}"/>
                        <DataGridTextColumn Header="D"
                          Binding="{Binding d}"/>
</DataGrid>

where Dataset:

var Dataset = await_apiDataService.GetDataSet();

            if (Dataset != null)
            {
                Dataset.Clear();
                foreach (var item in Dataset)
                {
                    Dataset.Add(item);
                }

Solution

  • You can create a separate class with exactly the fields that you want to display

    var response = await_apiDataService.GetDataSet();
    
    if (response != null)
    {
        var dataVMs = response.Select(t=> new DataViewModel{ }).ToList();
        Dataset.Clear();
        Dataset.AddRange(dataVMs);
    }
    
    class DataViewModel 
    {
        //Add fields here
    
    }
    

    Or you can change your xaml to use ListView instead of DataGrid and then style the listview template accordingly.