deeperzone
deeperzone

Reputation: 5

Display member of class in DataGridView

I have two classes:

public class Client
    {
     public int Id {get; set;}
     public string Name {get; set;}
     public AboutClient ClientInfo {get; set;}

     public Client (int id, string name, AboutClient aboutClient)
     {
      Id = id;
      Name = name;
      ClientInfo = aboutClient;
     }
    }

 public class AboutClient
    {
     public int Id {get; set;}
     public string LastName {get; set;}

     public AboutClient(int id, string lastName)
     {
      Id = id;
      LastName = lastName;
     }
    }

I've created a list and bound it to a datagridview

    public void BindData()
    {
     List<Client> clients = new List<Client>();

     clients.Add(new Client(1, "Joy", new AboutClient(1, "Smith")))

     dataGridViewClient.DataSource = clients;
    }

I get the following data in dgw:

1       "Joy"      AboutClient

How to display AboutClient.LastName instead "AboutClient" ?

Upvotes: 0

Views: 1932

Answers (2)

Blorgbeard
Blorgbeard

Reputation: 103525

Easiest way is to hide the ClientInfo column:

[Browsable(false)]
public AboutClient ClientInfo {get; set;}

And add a new column that returns the lastname from the client info:

public string LastName { get { return ClientInfo.LastName; } }

Upvotes: 1

David
David

Reputation: 4983

Add this to AboutClient

public override string ToString()
{
    return LastName;
}

Upvotes: 0

Related Questions