How can I display the data from an excel sheet in a Windows Community Toolkit DataGrid?

73 views Asked by At

I have an excel sheet that I want to display in a DataGrid. My issue is that I don't know what kind of data structure to put in the ObservableCollection so that the rows will show properly. I know this sort of thing works with a struct holding the row data, but a struct with 20 some fields seems messy to me.

1

There are 1 answers

0
Andrew KeepCoding On

If you don't want a class that represents a row, you can put them in a List.

private ObservableCollection<List<object>> Items { get; } = new()
{
    new List<object> { "1", "John", true },
    new List<object> { "2", "Mary", false },
    new List<object> { "3", "Bob" , true },
};
<toolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{x:Bind Items, Mode=OneWay}">
    <toolkit:DataGrid.Columns>
        <toolkit:DataGridTextColumn
            Binding="{Binding [0]}"
            Header="ID" />
        <toolkit:DataGridTextColumn
            Binding="{Binding [1]}"
            Header="Name" />
        <toolkit:DataGridCheckBoxColumn
            Binding="{Binding [2]}"
            Header="Check" />
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>

You can also use a Dictionary for this:

private ObservableCollection<Dictionary<string, object>> _test = new()
{
    new Dictionary<string, object>
    {
        { "Id", 1 },
        { "Name", "John" },
        { "Checked", true },
    },
    new Dictionary<string, object>
    {
        { "Id", 2 },
        { "Name", "Mary" },
        { "Checked", false},
    },
    new Dictionary<string, object>
    {
        { "Id", 3 },
        { "Name", "Bob" },
        { "Checked", true },
    },
};
<toolkit:DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{x:Bind Items, Mode=OneWay}">
    <toolkit:DataGrid.Columns>
        <toolkit:DataGridTextColumn
            Binding="{Binding [Id]}"
            Header="ID" />
        <toolkit:DataGridTextColumn
            Binding="{Binding [Name]}"
            Header="Name" />
        <toolkit:DataGridCheckBoxColumn
            Binding="{Binding [Checked]}"
            Header="Checked" />
    </toolkit:DataGrid.Columns>
</toolkit:DataGrid>