Reputation: 16143
How can I create a DataGrid table with a variable number of columns?
Example: Assuming we have a list of integer lists List<List<int>>
. All inner lists have the same length n
. Now I would like to create a row per integer list and for each integer an extra column.
For example: For the two integer lists {1, 2, 3}
and 4, 5, 6
the DataGad would look like this:
1 | 2 | 3
--+---+---
4 | 5 | 6
Normally, I create an own class for my DataGrid row elements, like
class MyDataGridRecord {
public int first { get; set; }
public int second { get; set; }
...
}
But since I do not know how many columns I have, I can not write such a class with a fixed number of fields.
Upvotes: 0
Views: 549
Reputation: 101681
I suppose you can do something like this:
var list = new List<List<int>>
{
new List<int>() {2, 3, 4, 5},
new List<int>() {2, 3, 4, 5},
new List<int>() {2, 3, 4, 5},
new List<int>() {2, 3, 4, 5}
};
var columnCount = list[0].Count;
for (int i = 0; i < columnCount; i++)
{
dataGridView1.Columns.Add(i.ToString(),"Column " + i+1);
}
for (int k = 0; k < list.Count; k++)
{
dataGridView1.Rows.AddCopy(0);
}
for (int k = 0; k < list.Count; k++)
{
for (int i = 0; i < list[k].Count; i++)
{
dataGridView1.Rows[k].Cells[i].Value = list[k][i];
}
}
Upvotes: 1