Hello. I have this question. Suppose there is a DataGrid that should display data from a table, a two-dimensional array, a list of lists, or a similar structure. In other words, I do not know exactly how many rows and columns in this table. I just need to display a table of arbitrary size in the data grid. How can i do this? All the solutions that I saw provided that I knew the number of columns. I tried to do something

<Grid> <DataGrid Name="MyTableGrid" AutoGenerateColumns="True" > </DataGrid> </Grid> var resultDetails = new List<List<int>> { new List<int> { 1, 1, 1, 1, 1, 1 }, new List<int> { 2, 2, 2, 2, 2, 2 } }; PeriodicTableGrid.ItemsSource = resultDetails; 

But instead of the contents of the table, I get this:

alt text

Is it possible to somehow form a grid so that it displays the contents of the table regardless of its dimension?

  • one
    @JuniorTwo: maybe it will help: < stackoverflow.com/a/15221279/276994 >? - VladD
  • I could be wrong, but it seems to be not very wpf-style. I heard something about binding and so on. After all, there must be some simple means to fill the table, since there is such a component as a DataGrid - JuniorTwo
  • @JuniorTwo: The problem is this: untyped strings (and you have strings = arrays) are also not in wpf style. If instead of List<List<int>> , you would have List<SomeClass> , it would be much easier. What does your data really mean ? Do you really need an array, and not a more semantic type of string? - VladD
  • Well, in fact, I do not need an array of integers, I need the ability to display some information in a table. For example, SomeClass [] [] or int [] [] (type is not important, it is important to understand the principle itself how to display data in a table) - JuniorTwo

1 answer 1

DataGrid designed to display data of a table type: essentially, it needs a sequence of instances of the same class. So you use it for other purposes, hence the problem.

If you need to display many identical elements, I would advise UniformGrid + ItemsControl :

 <ItemsControl ItemsSource="{Binding FlattenedItems}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="10"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> 

and in code-behind

 public IEnumerable<SomeClass> FlattenedItems { get; set; } // ... SomeClass[][] items = /*...*/; FlattenedItems = items.SelectMany(x => x);