2

I am trying to easily visualise data in a GridView using the DataSource property. This works well for atomic data types, but for custom classes, C# doesn't know how to display them. How can you tell it how to display the item in a customised way?

The following code:

[DisplayName("Person")]
public class Person
{
    public Person(string first, string last)
    {
        FirstName = first;
        LastName = last;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[DisplayName("Some contract")]
public class Contract
{
    public Contract(Person employer, Person employee, int salary)
    {
        Employer = employer;
        Employee = employee;
        Salary = salary;
    }

    public Person Employer {get; set;}
    public Person Employee { get; set; }
    public int Salary { get; set; }
}

class MyGridView : GridView
{

    public MyGridView() 
    {
        Person[] people = { new Person("John", "Smith"), new Person("Adam", "Bell"), new Person("Kate", "Regan") };
        Contract[] contracts = { new Contract(people[0], people[1], 10000), new Contract(people[0], people[2], 30000) };
        this.DataSource = contracts;
    }
}

Produces this:

enter image description here

Ideally, where now it says GridReportForm+Person, I'd like it to say "John Smith", "Adam Bell" etcetera. Is there any way to accomplish this?

4

1 回答 1

4

是的,只需覆盖Object.ToString()并返回一个适合显示的字符串。

public override string ToString()
{
    return string.Format("{0} {1}", FirstName, LastName);
}
于 2013-09-30T15:48:54.987 回答