Search code examples
c#wpfdatagridexpandoobject

C# WPF DataGrid - ExpandoObject in loop


I have some problem with that code. What am I doing wrong?

List<dynamic> list = new List<dynamic>();
var columnBind = columnBindName(); // {id, n0, n1, etc...} Name of Columns Bind

list.Add(new ExpandoObject());

foreach (var c in columnBind)
{
    list[0].c = "something";    //not working in Datagrid
    Console.Write(list[0].c);   //in console i have "something"
    list[0].id = "hello";       //working in Datagrid
}

Solution

  • Assuming you want to set property names defined in custom list and that columnBindName is some sort of string enumerable you can use feature that ExpandoObject implements IDictionary<string, object> interface which allows you to get/set property value by string name

    foreach (var c in columnBind)
    {
        (list[0] as IDictionary<string, object>)[c] = "property value";
    }