0

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.

3 Answers 3

1

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" }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.