Fill a Datagrid with data from a list but stating which columns I want to display

Asked

Viewed 171 times

1

Dear colleagues.

I want to fill a Datagrid from a list. The detail is that I want to select the columns to be displayed. If you do not inhibit auto generation of the columns, the data will normally exist. But if it inhibits auto generation, it shows the created columns + the database columns, but does not display the data.

Follows part of the routine:

  private void frmCFOPPesquisar_Load(object sender, EventArgs e)
    {
        dgvPesquisar.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

        dgvPesquisar.AutoGenerateColumns = false;

        ConfiguraDGV();

        CarregarGrid();
    }

    public void ConfiguraDGV()
    {
        dgvPesquisar.Columns.Add("cfop", "CFOP");
        dgvPesquisar.Columns.Add("Descricao", "Descrição");
        dgvPesquisar.Columns.Add("NaturezaOperacao", "Natureza de Operação");            
    }

    public void CarregarGrid()
    {
            BancoContexto contexto = new BancoContexto();

            IEnumerable<Cfop> lista = from p in contexto.Cfops select p;

            dgvPesquisar.DataSource = lista.ToList();
    }

Thank you.

  • You have to set the column dataproperty with the name of the property of the object in the list

1 answer

1

Set the column dataproperty:

dgvPesquisar.Columns["cfop"].DataPropertyName = "CFOP";
  • Perteito rovann. It worked. Thank you very much.

  • @GVGTEC do not forget to mark as reply, thank you

Browser other questions tagged

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