Bind DataGrid to List<Dictionary<string,string>>

446 Views Asked by At

I'm loading my datagrid columns dynamically as the number of columns may vary in runtime. The list of column names are retrieved in the ProdCatList.I want to simulate adding a single row into my QuotationDG Datagrid.

Here's how I add my columns:

 foreach (ProductCategory ProdCat in ProdCatList)
 {
      DataGridColumn ProdCatColumn = new DataGridTextColumn {Binding = new Binding(ProdCat.Name)};
      ProdCatColumn.Header = ProdCat.Name;
       QuotationDG.Columns.Add(ProdCatColumn);
 }

This is how I'm trying to add the dummy row:

List<Dictionary<string, string>> mydictlist = new List<Dictionary<string,string>>();
Dictionary<string, string> mydict = new Dictionary<string, string>();
for (int i=0; i<ProdCatList.Count; i++)
{

    mydict.Add(ProdCatList[i].Name, ProdCatList[i].Name);
  }
  mydictlist.Add(mydict);

 QuotationDG.ItemsSource = mydictlist;
}

For the first code, the columns display correctly, but for the second code a row is added to the DataGrid but the Names (in the dictionary values) are not displayed and all columns are blank. How can I fix this code to show the data in the added row?

1

There are 1 best solutions below

1
On

your mydist type will use same object if you define it outside the loop

for (int i=0; i<ProdCatList.Count; i++)
{
   Dictionary<string, string> mydict = new Dictionary<string, string>();
    mydict.Add(ProdCatList[i].Name, ProdCatList[i].Name);
}
  mydictlist.Add(mydict);