How to display the values of two-class fields in a Datagridview?

Asked

Viewed 61 times

1

I’m populating an object DataGridView with a list of type classes List<Curso>, and the way I populate the DataGridView is as follows:

meuDataGridView.DataSource = cursos;

But one of the fields of my class Curso is another class, which in this case is the class Instituicao. And in the data display on the grid the field Nome class Instituicao does not appear correctly.

Here is an illustration of the data in the grid:

ilustração do DataGridView

Reproducing the minimum example

To reproduce the minimum example of the problem illustration, you will need the class Curso class Instituicao and a form with DataGridView.

Class Course:

class Curso
{
    public string Descricao { get; set; }
    public int CargaHoraria { get; set; }
    public Instituicao Instituicao { get; set; }
}

Class Institution:

public class Instituicao
{
    public string Nome { get; set; }
}

Class of the form with the DataGridView and data populated in it:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var cursos = new List<Curso>
        {
            new Curso
            {
                Descricao = "Curso Java",
                CargaHoraria = 99999999,
                Instituicao = new Instituicao
                {
                    Nome = "Instituicao Javali"
                }

            },
            new Curso
            {
                Descricao = "Curso Python",
                CargaHoraria = 1,
                Instituicao = new Instituicao
                {
                    Nome = "Monty Python"
                }
            },
            new Curso
            {
                Descricao = "Curso de PHP",
                CargaHoraria = -99999999,
                Instituicao = new Instituicao
                {
                    Nome = "Instituicao no fim da galaxia"
                }
            }
        };

        PopulaGrid(cursos);
    }

    private void PopulaGrid(List<Curso> cursos)
    {
        if (cursos != null && cursos.Any())
        {
            dataGridView.DataSource = cursos;
        }
    }
}

Question

How can I display property value Nome class Instituicao on the grid instead of that unusual value?

  • new Curso { Descricao = "Curso Java", CargaHoraria = 99999999, Nome = "Instituicao Javali" }?

  • @Maniero the class Instituicao has more fields, this is just one example :)

2 answers

2

As your Institution class has only one property, perhaps the appropriate would be to place it within course. But it depends on how you want to use it later. Other solutions would be to override the ToString printing the name of the institution:

public class Instituicao
{
    public string Nome { get; set; }

    public override string ToString()
    {
        return Nome;
    }
}

Or create an anonymous object with the complete data:

private void PopulaGrid(List<Curso> cursos)
{
    if (cursos != null && cursos.Any())
    {
        dataGridView1.DataSource = cursos.Select(c => new { c.CargaHoraria, c.Descricao, Instituição = c.Instituicao.Nome }).ToList();
    }
}

2


You can use several ways:

Anonymous object:

dataGridView1.DataSource = cursos.Select(x=> new { Descrição = x.Descricao, Instituição = x.Instituicao.Nome  }).ToList();

Add a Course property that returns only the Name of the Institution:

public class Curso
{
    public string Descricao { get; set; }
    public int CargaHoraria { get; set; }
    public Instituicao Instituicao { get; set; }

    public string InstituicaoNome => this.Instituicao.Nome;
}

Overwrite the Tostring method, but this only applies in one property:

public class Instituicao
{
    public string Nome { get; set; }

    public override string ToString()
    {
        return this.Nome;
    }
}

Or, format the value during the Datagridview Cellformating event:

private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
    if (column.DataPropertyName.Contains("."))
    {
        object data = dataGridView1.Rows[e.RowIndex].DataBoundItem;
        string[] properties = column.DataPropertyName.Split('.');
        for (int i = 0; i < properties.Length && data != null; i++)
            data = data.GetType().GetProperty(properties[i]).GetValue(data);
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = data;
    }
}

The latter, I find the most expensive, and was taken from Soen: https://stackoverflow.com/a/35863096/4713574

It is not directly connected, but related: How to get the value of a property with Expression

Browser other questions tagged

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