Search code examples
c#wpfdata-bindingwpfdatagrid

DataGridView databinding to List<List<KeyValuePair<string,string>>>


I am trying to bind the itemssource property of my datagridview to a list of objects whose property names I will not know until runtime.

The code currently compiles but nothing shows up in the columns (the datagrid shows a row for each item in my list, but nothing in each column)

setting up column bindings

foreach (KeyValuePair<string, string> pair in _columns)
{
    Microsoft.Windows.Controls.DataGridTextColumn textCol = new Microsoft.Windows.Controls.DataGridTextColumn();
    textCol.Header = pair.Key;
    textCol.Binding = new Binding(pair.Value);
    ItemListDataGrid.Columns.Add(textCol);
}

example hard-coded List:

List<List<KeyValuePair<string,string>>> itemSet = new List<List<KeyValuePair<string,string>>>();
List<KeyValuePair<string,string>> item1 = new List<KeyValuePair<string,string>>();
item1.Add(new KeyValuePair<string,string>("ACTION","ACTION"));
itemSet.Add(item1);
ItemListDataGrid.ItemsSource = itemSet;

Any ideas how to get this to work?


Solution

  • Using a DataTable that is populated dynamically, I was able to solve this problem relatively quickly. The expando object would also work, but I only need to load the objects into a datagridview for selection, and have no need of them after that point. Because of this, I decided not to go with the expando object in this situation.