Format numerical field with 2 decimal places in datagridview C #

-2

I need to show a column in the datagridview column of gross weight this format 0.00, but I'm not getting it, this column is not created in any database, I created the direct column in the datagridview, I already went in the numeric formatting of the column, I left as N2, and even then nothing to format the column. I need when I type a decimal number in the column, EX digit 10 when exiting the cell, need to show 10.00

Follow my code:

    private void btn_xml_Click(object sender, EventArgs e)
    {
        string FileName = @"C:\Xml_Entrada\" + txt_chave.Text + ".xml";
        List<ClasseItensXml> ListaItens = new List<ClasseItensXml>(); //A lista é do tipo ClasseItensXml
        XmlDocument doc = new XmlDocument();
        doc.Load(FileName);
        var proditens = doc.GetElementsByTagName("prod");

        foreach (XmlElement nodo in proditens)
        {
            ListaItens.Add(
                 new ClasseItensXml()
                 {
                     CodigoProduto = nodo.GetElementsByTagName("cProd")[0].InnerText.Trim(),
                     NomeProduto = nodo.GetElementsByTagName("xProd")[0].InnerText.Trim(),
                     QuantidadeComercializada = nodo.GetElementsByTagName("qCom")[0].InnerText.Trim()
                 });

            //Repare que cada "nodo" é um item, portanto só adiciona um ClasseItensXml na lista.
        }

        dgw_Xml.DataSource = ListaItens; //por fim, usa a lista de source

        dgw_Xml.Columns["PesBruto"].DefaultCellStyle.Format = "N2";
    }

    
asked by anonymous 17.07.2018 / 22:09

1 answer

0

The column you created has no associated properties, so the DataGridView treats as a string and does not format with N2 .

You can change your ClasseItensXml class to add the PesoBruto property and associate this column:

public class ClasseItensXml
{
    public string CodigoProduto {get;set;}
    public string NomeProduto {get;set;}
    public string QuantidadeComercializada {get;set;}
    public decimal PesoBruto {get;set;}
}

The rest remain the same, but now the DataGridView knows that it is a numeric type and does the formatting.

  

Do not forget to associate the column with the property with DataPropertyName and the formatting you can also do with the graphical interface of visual studio.

    
18.07.2018 / 02:32