Unknown Unknown - 16 days ago 5
C# Question

How to display custom field type on data grid view? [C# / WinForms]

I have employee class, which has field of type ISalary (Interface). In data grid view, I want to display that salary, but what I get is empty field. Is it any possible way to display that "custom type field" in data grid view? invoking toString method would help, but I can't understand how to do that.
Here is how I am binding data:

employeeBindingSource.DataSource = employeesList;


All fields in that list, ofc is not null. And here is some of my class, which list I want to display:

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int DepartmentId { get; set; }

// how to display this?
public ISalary Salary { get; set; }

...
}


I did some research and could not find any example on it. Or maybe was not trying hard enough.:/

Answer

Since you are using a interface as type of property, you can not override ToString method for that ISalary type without knowing the concrete type. So if you know a Salary class which implemented that interface and used instead of that interface at run-time, you can override ToString of that type.

But, in general it's not a good idea to rely on ToString of that concrete type, this way your program will be tightly relied on the concrete type and will loose its goal in using the interface.

Instead, you can use either of these options:

  • Use CellFormatting event to provide display value.
  • Use a DataGridViewComboBoxColumn which contains a List<Salary> but, set its display style property to nothing to not show dropdown button.
  • Use a readonly property in Employee class which return a known property of ISalary, like return this.Salary.SomeProperty;

And still there are more options. To see some other options and examples, take a look at this post: How to bind a column from second level list on bindsource in winforms datagridview or this one: Show Properties of a Navigation Property in DataGridView (Second Level Properties).