Binding DataGridView to implementing class in .NET
How should I bind my collection of T objects which implements an interface and adds more properties to a DataGrid? Here is an example:
// interface
public interface IPerson{
[DisplayName(@"FullName")]
string Name{ get; }
}
// implementation
public class Employee : IPerson{
[DisplayName(@"Net Salary")]
public int Salary {
get { return 1000; }
}
public string Name{
get { return "Foo"; }
}
// collection
SortableBindingList<IPerson> MyList { get; set }
...
...
MyList.Add(new Employee());
...
dataGridView.DataSource = MyList;
When I do this, it only b开发者_运维百科inds Name but not Salary.
Is there any way to bind to both the properties (Name and Salary in this case)? Thanks.
It is because of Salary
is not in your IPerson
interface definition.
You should either add Salary to your IPerson
interface and implement that in your Employee
class or change your MyList property definition as below;
SortableBindingList<Employee> MyList { get; set }
Edit After Comments
You can achive your goal by implementing ITypedList
. It is not a trivial task. So i would not recommend you to do that if you do not have to.
You may inherit from SortableBindingList<IPerson>
and implement ITypedList
. You should also create a custom PropertyDescriptor
to get it work.
Here is a good article about the subject Virtual Properties that i have just found. (The article is the first result of searching the ITypedList and PropertyDescriptor keywords together by the time being).
Hope this help.
Name
is in your interface, but Salary
isn't. Add Salary
to your interface and it should work fine.
If you don't want to change your interface, use SortableBindingList<Employee> MyList
instead of SortableBindingList<IPerson> MyList
You can force the DataGridView to look at the actual objects instead of the interface by casting to object. In my example I use VB.NET but it is probably not hard for you to translate to C#.
dataGridView.DataSource = New SortableBindingList(Of Object)(MyList.Cast(Of Object).ToList())
In my case MyList is an IList(Of IPerson)
.
精彩评论