Click here to Skip to main content
15,892,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 = "address"";
p.AddProperty<datetime>("BirthDate", DateTime.Now);

List<person> lstPerson=new List<person>();

lstPerson.Add(p);</person></person></datetime>



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.
Posted
Updated 20-Jun-11 17:28pm
v4

1 solution

Your class needs to implement the ICustomTypeDescriptor interface. The framework queries this interface when it needs to know what are the properties of your type. I wrote an article on a very similar subject a while ago. In fact, I used a Person class as well. In my case, I was creating baseline properties, such as Address1, Address2, etc. Unlimited baselines for any class[^]

However, for simplicity, you may choose a much simpler road that may still work. Make your Person class inherit from DataTable and have a single DataRow in it. Add columns when you add custom properties.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900