My class is like this,
public class Person : DynamicObject
{
public string Name { get; set; }
public string Address { get; set; }
Dictionary<string, object> dictionary = new Dictionary<string, object>();
public int Count
{
get
{
return dictionary.Count;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name;
return dictionary.TryGetValue(name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dictionary[binder.Name] = value;
return true;
}
public void AddProperty<TTValue>(string key, TTValue value = default(TTValue))
{
dictionary[key] = value;
}
public void AddProperty(string typeName, string key, object value = null)
{
Type type = Type.GetType(typeName);
dictionary[key] = Convert.ChangeType(value, type);
}
}
Then I’m creating objects from this class and add it to a list
dynamic p = new Person();
p.Name = "john";
p.Address = "address1";
p.AddProperty<DateTime>("BirthDate", DateTime.Now);
p.AddProperty("System.String", "Weigth", "70 kg");
List<Person> lstPerson=new List<Person>();
lstPerson.Add(p);
After add few person objects like this I bind this to a datagrid view using a binding source. But after bound to the grid view my dynamically created properties are not shown in the grid.
When I have a list of generic objects which need to be bound to a grid, I like to use a Linq select statement.
Then you can use the property names you defined to access the columns.