Get binded value from class property, DefaultBindi

2019-05-22 22:27发布

I'm creating some entities (class) for my project and I want to set a default binging property for it, here is an example

namespace MyNamespace
{
    [System.ComponentModel.DefaultBindingProperty("Name")]
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Gender { get; set; }
    }

    public class Family
    {
        public int ID { get; set; }
        public Person Father { get; set; }
    }
}

if I have List<Family> and want to bind it to a GridView and added this field <asp:BoundField DataField="Father" /> the result will be MyNamespace.Person but I need it to populate the value of the property Name without using TemplateField so did I miss something? or DefaultBindingProperty is not the right Attribute ?

1条回答
做个烂人
2楼-- · 2019-05-22 23:22

The problem is the the property Father is of the type Person. There is no obvious string representation of a Person value, so the name of the type is displayed. Try to override the ToString method to show what you want:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Gender { get; set; }
    public override string ToString()
    {
        return Name;
    }
}
查看更多
登录 后发表回答