您可以自定义类在GridView中的显示方式吗?

时间:2013-09-30 15:47:14

标签: c# gridview attributes

我正在尝试使用GridView属性轻松地在DataSource中可视化数据。这适用于原子数据类型,但对于自定义类,C#不知道如何显示它们。如何告诉它如何以自定义方式显示项目?

以下代码:

[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;
    }
}

产生这个:

enter image description here

理想情况下,现在它说GridReportForm+Person,我想说“John Smith”,“Adam Bell”等等。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:4)

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

public override string ToString()
{
    return string.Format("{0} {1}", FirstName, LastName);
}