0
public class Customer
{
    public int id { get; set; }
    public Person CustPerson { get; set; }
    public Customer()
    {
        this.CustPerson = new Person();
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

private void button1_Click(object sender, EventArgs e)
{
    List<Customer> CustomerList=new List<Customer>();
    for (int i = 0; i <= 4; i++)
    {
        Customer cust = new Customer();
        cust.id = i;
        cust.CustPerson.FirstName = "john" + i.ToString();
        cust.CustPerson.LastName = "deo" + i.ToString();
        cust.CustPerson.Age = 20 + i;
        CustomerList.Add(cust);
    }
    dataGridView1.DataSource = CustomerList;
}

我希望firstname, lastname&age打印在 中gridview,但我得到一列,而不是三列,其中包含mynamespace.person:-(

帮帮我......任何帮助表示赞赏。

4

3 回答 3

1

您只需选择CustPerson属性 (Linq):

CustomerList.Add(cust.Select(c => c.CustPerson).ToArray());

还要确保GridViewAutoGenerateColumns设置为 true。

于 2012-09-29T05:44:49.943 回答
0
public partial class Form1 : Form
{
    DataGridViewCheckBoxColumn Column;
    CheckBox checkbox;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        List<Customer> CustomerList = new List<Customer>();
        for (int i = 0; i <= 4; i++)
        {
            Customer cust = new Customer();
            cust.id = i;                 
            cust.FirstName = "john" + i.ToString();
            cust.LastName = "deo" + i.ToString();
            cust.Age = 20 + i;
            CustomerList.Add(cust);
        }
        dataGridView1.AutoGenerateColumns = true;
        dataGridView1.DataSource = CustomerList;            
    }
}
public class Customer:Person
{
    public int id { get; set; }       
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
于 2012-12-14T07:00:03.030 回答
0

与此处描述的过程类似,您可以为 GridView 设置列以显示您喜欢的任何信息

     <asp:TemplateField HeaderText="First Name" SortExpression="CustPerson.FirstName">
         <ItemTemplate>
             <asp:Label ID="lblCustomerFirstName" runat="server" Text=''<%# ((Person)Eval("CustPerson")).Firstname %>''></asp:Label>
         </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Last Name" SortExpression="CustPerson.LastName">
         <ItemTemplate>
             <asp:Label ID="lblCustomerLastName" runat="server" Text=''<%# ((Person)Eval("CustPerson")).LastName %>''></asp:Label>
         </ItemTemplate>
     </asp:TemplateField>
     <asp:TemplateField HeaderText="Age" SortExpression="CustPerson.Age">
         <ItemTemplate>
             <asp:Label ID="lblCustomerAge" runat="server" Text=''<%# ((Person)Eval("CustPerson")).Age %>''></asp:Label>
         </ItemTemplate>
     </asp:TemplateField>
于 2012-09-29T07:21:53.190 回答