1
I have a table with the following fields in the order they were created:
idProdReceita, idReceita, Quantidade, Imagem, Descricao, Fornecedor, Medida, Unidade, Valor
When I load the Datagridview in the program the columns appear with the Default names of the fields. So far everything normal.
** What I really want is to change the names of the columns after changing their order and visibility. I don’t want to show all fields in Datagridview.
If I try to change the names of the Datagridview columns programmatically as shown below, it works:
        gridView.Columns["idReceita"].HeaderText = "ID";
        gridView.Columns["Imagem"].HeaderText = "Imagem";
        gridView.Columns["Descricao"].HeaderText = "Descrição";
        gridView.Columns["Unidade"].HeaderText = "Unidade";
        gridView.Columns["Quantidade"].HeaderText = "Quant.";
        gridView.Columns["Exclusao"].HeaderText = "Exclusão";
P.S. The last column shown [delete] is a button I entered into Datagridview at runtime.
Below you can see how Datagridview is already with the columns and visibilities changed:
Columns I want to appear in datagridview (changed order and visibility):
idReceita, Imagem, Descricao, Unidade, Quantidade, Exclusao
Names I want to appear in place of the default columns:
ID, Image, Description, Unit, Quantity, Deletion
**The problem occurs when I change the order and visibility of some columns (Visible = false) and use a method to automate the name change. Only the first column changes the name, the rest continues with the default name.
Method used:
private void TrocaNomeColuna(DataGridView gridView, string nomeCampo, string novoNome)
    {
        string[] campo = nomeCampo.Split(',');
        string[] titulo = novoNome.Split(',');
        try
        {
            for (int i = 0; i < campo.Length; i++)
            {
                if (gridView.Columns.Contains(campo[i]))
                {
                    gridView.Columns[campo[i]].HeaderText = titulo[i];
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
Use:
Trocanomecoluna(grid, "idReceita, Imagem, Descricao, Unidade, Quantidade, Exclusao", "Id, Imagem, Descrição, Unidade, Quantidade, Exclusão");
Image of how Datagridview looks after running the program using the method:
Here you notice that after using the method only the first column was affected; the remainder continued showing the default names of the columns;
I have a method that allows me to hide and change the order of the columns, at least that works.


The worst is that I had already thought about it a few minutes before your reply. I just hadn’t implemented the code yet. But, what you said really worked. However I ended up changing the parameters of the type string in List<string> with this eliminated some variables. Thank you so much for the tip.
– Oto Emerson