How to view data from various tables in Datagridview?

Asked

Viewed 161 times

0

I’m trying to display several tables on DataGridView, from a database that is Entity Framework.

Example, person table, address.

I tried to use pessoa.BindingSource, then comes the address list, but I could not call the types of addresses {logradouro, cidade, bairro, estado}

The structure the Person table is using to define the items/table data is:

public virtual ICollection<enderecos> enderecos { get; set; }
  • 1

    You must create a new object containing the / column attributes that must be displayed in Gridview to expose a "Tabular"

1 answer

0

You have to create a new class, to be used as a "ViewModel", or use anonymous objects:

Class:

public class PessoaViewModel
{
    public string Nome {get;set;}
    public string Endereco {get;set;}
}

Source:

var result = Pessoas.Select(x => new PessoaViewModel(){ Nome = x.Nome, Endereco = x.enderecos.First().Logradouro + ", " + x.enderecos.First().Cidade }).ToList();

dgv.DataSource = result;

Using anonymous objects:

var result = Pessoas.Select(x => new { Nome = x.Nome, Endereco = x.enderecos.First().Logradouro + ", " + x.enderecos.First().Cidade }).ToList();

dgv.DataSource = result;

ps. Simple example without error handling. It is possible that the person has more than one address, so you have to decide which logic will be used to display.

  • I am using Anonymous Types, but I would like to display them with a formatting, for example the zip code: ___- __ or a telephone () -. In the database are saved as string with the numbers without the dots and dashes.

Browser other questions tagged

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