C # - Instance property name in a DataGridView

2

I have a Products class with the following attributes:

public class Produto
{
    public int cod { get; set; }
    public string codBarras { get; set; }
    public string nome { get; set; }
    public Categoria categoria { get; set; }
    public Decimal precoCompra { get; set; }
    public Decimal precoVenda { get; set; }
    public Decimal qtdEstoque { get; set; }
    public string descricao { get; set; }

}

The Category class is as follows:

 public class Categoria
{
    public int cod { get; set; }
    public string nome { get; set; }
}

When I want to list the products in a DataGridView, I want the Product lines to have in the "Category" column with the "name" property of the instance of the Category class that is within the Product instance.

But it is showing up at the time of listing the products in the DataGridView:

Propertyofthe"Category" column in DataGridView properties:

HowProductinstancesarebeingcreatedintheSELECTImakeinthedatabase:

Produtoprod=newProduto();prod....(outroscampos)prod.categoria=CategoriaDAO.getCategoria(leitorSQL.GetInt32("codCategoria"));

This getCategory () method returns an instance of the Category class according to the category code of a product.

Some questions:

1 - Is there a way to do this?

2 - Is it a good programming practice to put (in this example) the objects of type Product have an attribute of type Category? Or would it be better to create two variables? Being one for the category code and another for the Category name.

    
asked by anonymous 04.06.2018 / 14:33

1 answer

1

This response I just pasted the SO in English, from the following post: link

In general, it seems the DataGridView has nothing ready to do this. But its object assembly is perfect (especially if you work with EntityFramework).

The English OS gave an interesting solution using a DataGridView formatting event and giving the result when you use objects inside objects:

private void Grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{

    DataGridView grid = (DataGridView)sender;
    DataGridViewRow row = grid.Rows[e.RowIndex];
    DataGridViewColumn col = grid.Columns[e.ColumnIndex];
    if (row.DataBoundItem != null && col.DataPropertyName.Contains("."))
    {
        string[] props = col.DataPropertyName.Split('.');
        PropertyInfo propInfo = row.DataBoundItem.GetType().GetProperty(props[0]);
        object val = propInfo.GetValue(row.DataBoundItem, null);
        for (int i = 1; i < props.Length; i++)
        {
            propInfo = val.GetType().GetProperty(props[i]);
            val = propInfo.GetValue(val, null);
        }
        e.Value = val;
    }
}
    
04.06.2018 / 14:40