Object List(with some objects as attributes) for Datagridview - C#

Asked

Viewed 304 times

0

How do I show the Street or Zip Code of the list below in Datagridview.

People’s List (to display in datagridview)

List<Pessoa> Pessoas;

Classe Pessoa

using System;

public class Pessoa
{
    public int id { get; set; }
    public string Nome { get; set; }
    public Endereco Endereco { get; set; }
}

Address class

using System;

public class Endereco
{
    public int id { get; set; }
    public string Rua { get; set; }
    public string cep { get; set; }
}

My intention is to change the value that appears. The folder is showing plus the class: Model.Endereco

  • How are you doing the bind datagrid?

  • 'Bindingsource Bs = new Bindingsource();' 'Bs.Datasource = _List_nfgerar;' 'dgvNotas.Datasource = null;' 'dgvNotas.Datasource = Bs;'

  • Well, it’s certainly duplicated the question I pointed out. If you look there, you’ll get your solution.

1 answer

1


Use the Linq to format the data, the DataGridView does not accept grouped objects, or list of a main object, and even rewriting ToString(), that I see as wrong technique, could not bring the two fields that are essential to your consultation.

Make an expression with Linq thus:

GridView.DataSource = Pessoas.Select(x => new 
{
  x.id,
  x.Nome,
  Rua = x.Endereco.Rua,
  Cep = x.Endereco.Cep
})
.ToList();

Links:

  • 1

    Good afternoon Virgilio Novic. Your solution has served me perfectly. Thank you.

  • Good afternoon jbueno. Thank you for the link of the question that had been asked earlier.

  • for nothing @Luismedeiros ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.