tags:

views:

183

answers:

3

I'm trying to create a datagrid with a variable number of columns and rows. I can create the columns but I don't know how to insert the content.

_dataGrid.Columns.Add(new DataGridTextColumn { Header = "Column 0",
                                                            Binding = new Binding("0")

                                                            }
                                  );

I have all of the data that I want to add in a string[,]. I don't understand how to prepare a data structure that implements IEnumerable so that I can set

_dataGrid.ItemsSource = GenerateData();//I'd expect to return a Dictionary["0"]=List<string>(){"1","2","3"} to bind to but it doesn't work

What is the data structure that I need to return from GenerateData if I wanted to include a column that had "1", "2", "3"?

Thanks in advance.

A: 

I hit this last night, I wanted to manually add content to different rows and cells etc.

You can do it programmatically by saying:

Grid.SetRow(myUserControl, 1);
Grid.SetColumn(myUserControl, 1);

myGrid.Children.Add(myUserControl);

It does completely bypass the databinding model, but sometimes that's just what you need.

TreeUK
I'm trying to use a DataGrid, not the Grid at this point.
fran
A: 

In the final analysis, the ItemsSource just has to be an object that implements IEnumerable. The objects which constitute the collection have to have a property that matches the Binding you set on the column. A DataTable is probably the most natural place to get started.

PeterAllenWebb
A: 

the ItemSource can really be anything... I demonstrate below an array of anonymous types, but you'd have to use named types if you want 2-way data binding (anonymous types generate a 1-way binding)

grid.Columns.Add(new DataGridTextColumn { 
    Header = "Foo",
    Binding = new Binding("Foo")
});

grid.Columns.Add(new DataGridTextColumn { 
    Header = "Bar",
    Binding = new Binding("Bar")
});

grid.ItemsSource = new [] {
   new { Foo = "asdf", Bar = "asdf" },
   new { Foo = "asdf", Bar = "asdf" },
   new { Foo = "asdf", Bar = "asdf" }
}
Jimmy