Format numeric field with 2 decimal places in datagridview c#

Asked

Viewed 284 times

-2

I need to show a column in the raw weight column datagridview this format 0.00, but I’m not getting, this column is not created in any database, I created the column directly in datagridview, I’ve been in the column numeric formatting, I left it as N2, and still no formatting of the column. I need that when I type a decimal number in the column, EX type 10 when leaving 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";
    }

inserir a descrição da imagem aqui

  • 4

    Young man, I ask you from the bottom of my heart to format the code of this question.

1 answer

0


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

You can change your class ClasseItensXml to add the property PesoBruto 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 remains the same, but now Datagridview knows that it is a numeric type and does the formatting.

Don’t forget to associate the column with the property DataPropertyName and the formatting you can also do by the graphical interface of the visual studio.

  • 1

    Thank you very much Rovann, once again..

Browser other questions tagged

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