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)开发者_StackOverflow中文版;
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.
var dataSource = myList.Select(item=> new
{ Name = item.Key,
MainAddress = item.Address.First() });
grid.DataSource = dataSource;
grid.DataBind();
Then you can use the property names you defined to access the columns.
I would bet that your grid doesn't support dynamic types. If you absolutely must use a dynamic type for this, you'll probably have to use reflection to manually add columns to your grid, or just specify them yourself. My suggestion would be to refactor your code to get rid of the dynamic type. In my opinion, using dynamic types is usually a code smell (not that there aren't legitimate uses for them, but what I'm seeing you doing could be done just as well with anonymous types instead of dynamic).
精彩评论