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 (response != null)
{
Dataset.Clear();
foreach (var item in Dataset)
{
Dataset.Add(item);
}
CodePudding user response:
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.
CodePudding user response:
you can not add columns directly to DataGrid. you have to add them to DataGrid.Columns property:
<DataGrid ItemsSource="{Binding Dataset}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="A" Binding="{Binding a}"/>
<DataGridTextColumn Header="B" Binding="{Binding b}"/>
<DataGridTextColumn Header="D" Binding="{Binding d}"/>
<DataGrid.Columns>
</DataGrid>