Mask CURRENCY {en-us} in GridView C #

1

My problem is: I want to include a mask with the Brazilian currency in a GridView column.

I am using CultureInfo.CurrentCulture , but when I put it to run, in GridView only the first Row appears the mask and not the others.

Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DGVPrinterHelper;
using Npgsql;
using PagedList;
using static Operacao.RelatorioBD;

namespace Operacao
{
    public partial class RelatorioGridContaContabil : Form
    {
        public string valorContSql;

        public RelatorioGridContaContabil(string carregaGridRelat)
        {
            InitializeComponent();
            valorContSql = carregaGridRelat;
            carregaGridContabil();
        }

        private void carregaGridContabil()
        {
            try
            {
                NpgsqlConnection conn = new NpgsqlConnection(new EmpresaBD().connString);

                NpgsqlCommand command = new NpgsqlCommand(valorContSql, conn);
                command.CommandTimeout = 190;
                command.Connection = conn;
                command.CommandText = valorContSql;

                NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
                adapter.SelectCommand = command;
                conn.Open();

                DataSet gridSet = new DataSet();
                adapter.Fill(gridSet);

                BindingList<RelContabil> relcontabil = new BindingList<RelContabil>();

                foreach (DataRow a in gridSet.Tables[0].Rows)
                {
                    RelContabil relat = new RelContabil()
                    {
                        Id = a.ItemArray[0].ToString(),
                        RazaoSocial = a.ItemArray[1].ToString(),
                        Exercicio = a.ItemArray[2].ToString(),
                        Lucro = a.ItemArray[3].ToString(),
                    };
                    relcontabil.Add(relat);                    
                }

                RelatorioContabilDataGridView.DataSource = relcontabil;

                // Varredura para verificação de empresas iguais + a soma dos valores
                decimal valor = 0;

                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    for (int j = 1; j < RelatorioContabilDataGridView.RowCount; j++)
                    {
                        if (RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString() == RelatorioContabilDataGridView.Rows[j].Cells[0].Value.ToString() && i != j && j != i)
                        {
                            valor = decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString()) + decimal.Parse(RelatorioContabilDataGridView.Rows[j].Cells[2].Value.ToString());
                            RelatorioContabilDataGridView.Rows[i].Cells[2].Value = valor;
                            RelatorioContabilDataGridView.Rows.RemoveAt(j);
                        }
                    }
                }

                // 2ª Varredura para verificação de empresas iguais, pois à alguns itens que repetem por mais de 3 vezes
                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    for (int j = 1; j < RelatorioContabilDataGridView.RowCount; j++)
                    {
                        if (RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString() == RelatorioContabilDataGridView.Rows[j].Cells[0].Value.ToString() && i != j && j != i)
                        {
                            valor = decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString()) + decimal.Parse(RelatorioContabilDataGridView.Rows[j].Cells[2].Value.ToString());
                            RelatorioContabilDataGridView.Rows[i].Cells[2].Value = valor;
                            RelatorioContabilDataGridView.Rows.RemoveAt(j);
                        }
                    }
                }

                // Insere a máscara nas linhas do código Empresa.
                string EmpresaFormat;

                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    EmpresaFormat = RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString();                    
                    EmpresaFormat = String.Format(@"{0:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DGVPrinterHelper;
using Npgsql;
using PagedList;
using static Operacao.RelatorioBD;

namespace Operacao
{
    public partial class RelatorioGridContaContabil : Form
    {
        public string valorContSql;

        public RelatorioGridContaContabil(string carregaGridRelat)
        {
            InitializeComponent();
            valorContSql = carregaGridRelat;
            carregaGridContabil();
        }

        private void carregaGridContabil()
        {
            try
            {
                NpgsqlConnection conn = new NpgsqlConnection(new EmpresaBD().connString);

                NpgsqlCommand command = new NpgsqlCommand(valorContSql, conn);
                command.CommandTimeout = 190;
                command.Connection = conn;
                command.CommandText = valorContSql;

                NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
                adapter.SelectCommand = command;
                conn.Open();

                DataSet gridSet = new DataSet();
                adapter.Fill(gridSet);

                BindingList<RelContabil> relcontabil = new BindingList<RelContabil>();

                foreach (DataRow a in gridSet.Tables[0].Rows)
                {
                    RelContabil relat = new RelContabil()
                    {
                        Id = a.ItemArray[0].ToString(),
                        RazaoSocial = a.ItemArray[1].ToString(),
                        Exercicio = a.ItemArray[2].ToString(),
                        Lucro = a.ItemArray[3].ToString(),
                    };
                    relcontabil.Add(relat);                    
                }

                RelatorioContabilDataGridView.DataSource = relcontabil;

                // Varredura para verificação de empresas iguais + a soma dos valores
                decimal valor = 0;

                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    for (int j = 1; j < RelatorioContabilDataGridView.RowCount; j++)
                    {
                        if (RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString() == RelatorioContabilDataGridView.Rows[j].Cells[0].Value.ToString() && i != j && j != i)
                        {
                            valor = decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString()) + decimal.Parse(RelatorioContabilDataGridView.Rows[j].Cells[2].Value.ToString());
                            RelatorioContabilDataGridView.Rows[i].Cells[2].Value = valor;
                            RelatorioContabilDataGridView.Rows.RemoveAt(j);
                        }
                    }
                }

                // 2ª Varredura para verificação de empresas iguais, pois à alguns itens que repetem por mais de 3 vezes
                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    for (int j = 1; j < RelatorioContabilDataGridView.RowCount; j++)
                    {
                        if (RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString() == RelatorioContabilDataGridView.Rows[j].Cells[0].Value.ToString() && i != j && j != i)
                        {
                            valor = decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString()) + decimal.Parse(RelatorioContabilDataGridView.Rows[j].Cells[2].Value.ToString());
                            RelatorioContabilDataGridView.Rows[i].Cells[2].Value = valor;
                            RelatorioContabilDataGridView.Rows.RemoveAt(j);
                        }
                    }
                }

                // Insere a máscara nas linhas do código Empresa.
                string EmpresaFormat;

                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    EmpresaFormat = RelatorioContabilDataGridView.Rows[i].Cells[0].Value.ToString();                    
                    EmpresaFormat = String.Format(@"{0:%pre%\.0000}", RelatorioContabilDataGridView.Rows[i].Cells[0].Value = Convert.ToInt32(EmpresaFormat, CultureInfo.InvariantCulture));
                    RelatorioContabilDataGridView.Rows[i].Cells[0].Value = Convert.ToString(EmpresaFormat);
                }

                decimal MoedaFormat;

                for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++)
                {
                    MoedaFormat = Decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString());

                    MoedaFormat =  Convert.ToDecimal(RelatorioContabilDataGridView.Rows[i].Cells[2].Value = MoedaFormat.ToString("C2", CultureInfo.CurrentCulture));

                    RelatorioContabilDataGridView.Rows[i].Cells[2].Value = Convert.ToString(MoedaFormat);
                }

                QuantidadeLabel.Text = RelatorioContabilDataGridView.RowCount.ToString();
                conn.Dispose();
            }

            catch (NpgsqlException nex)
            {

            }
            catch (Exception ex)
            {
                //throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PrintDialog configImpressora = new PrintDialog();
            DialogResult result = configImpressora.ShowDialog();
        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            PageSetupDialog pageSetupDialog = new PageSetupDialog();
            PageSettings pageSettings = new PageSettings();
            pageSetupDialog.PageSettings = pageSettings;
            if (pageSetupDialog.ShowDialog() == DialogResult.OK)
            {
                pageSettings = pageSetupDialog.PageSettings;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DGVPrinter printer = new DGVPrinter();
            printer.Title = "Relatório Lucro Distribuído";
            printer.SubTitle = String.Format("Data: {0}", DateTime.Now.Date.ToString("dd/MM/yyyy"));
            printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            printer.PageNumbers = true;
            printer.PageNumberInHeader = false;
            printer.PorportionalColumns = true;
            printer.HeaderCellAlignment = StringAlignment.Near;
            printer.Footer = "Candinho";
            printer.FooterSpacing = 15;
            printer.PrintDataGridView(RelatorioContabilDataGridView);
        }
    }
}
\.0000}", RelatorioContabilDataGridView.Rows[i].Cells[0].Value = Convert.ToInt32(EmpresaFormat, CultureInfo.InvariantCulture)); RelatorioContabilDataGridView.Rows[i].Cells[0].Value = Convert.ToString(EmpresaFormat); } decimal MoedaFormat; for (int i = 0; i < RelatorioContabilDataGridView.RowCount; i++) { MoedaFormat = Decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString()); MoedaFormat = Convert.ToDecimal(RelatorioContabilDataGridView.Rows[i].Cells[2].Value = MoedaFormat.ToString("C2", CultureInfo.CurrentCulture)); RelatorioContabilDataGridView.Rows[i].Cells[2].Value = Convert.ToString(MoedaFormat); } QuantidadeLabel.Text = RelatorioContabilDataGridView.RowCount.ToString(); conn.Dispose(); } catch (NpgsqlException nex) { } catch (Exception ex) { //throw; } } private void button1_Click(object sender, EventArgs e) { Dispose(); } private void button2_Click(object sender, EventArgs e) { PrintDialog configImpressora = new PrintDialog(); DialogResult result = configImpressora.ShowDialog(); } private void button3_Click_1(object sender, EventArgs e) { PageSetupDialog pageSetupDialog = new PageSetupDialog(); PageSettings pageSettings = new PageSettings(); pageSetupDialog.PageSettings = pageSettings; if (pageSetupDialog.ShowDialog() == DialogResult.OK) { pageSettings = pageSetupDialog.PageSettings; } } private void button4_Click(object sender, EventArgs e) { DGVPrinter printer = new DGVPrinter(); printer.Title = "Relatório Lucro Distribuído"; printer.SubTitle = String.Format("Data: {0}", DateTime.Now.Date.ToString("dd/MM/yyyy")); printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip; printer.PageNumbers = true; printer.PageNumberInHeader = false; printer.PorportionalColumns = true; printer.HeaderCellAlignment = StringAlignment.Near; printer.Footer = "Candinho"; printer.FooterSpacing = 15; printer.PrintDataGridView(RelatorioContabilDataGridView); } } }
    
asked by anonymous 14.06.2018 / 18:35

2 answers

2

The first problem is that you are using RowCount and not .Rows.Count so it is traversing only the rows that are being displayed and not all rows in the collection. But that's not how the column is formatted.

To format, just set DefaultCellStyle :

RelatorioContabilDataGridView.Columns[2].DefaultCellStyle.Format = "C2";

But for this, the object's property must be numeric (decimal).

The Class should look something like this:

public class RelContabil
{
    public int Id {get;set;}
    public string RazaoSocial {get;set;}
    public string Exercicio {get;set;}
    public decimal Lucro {get;set;}
}

As I said, there are also other problems in the code. I recommend opening another question to resolve them, but I leave here how would be the execution of NpgsqlCommand :

private void carregaGridContabil()
{
    try
    {
        BindingList<RelContabil> relcontabil = new BindingList<RelContabil>();
        using (NpgsqlConnection conn = new NpgsqlConnection("string conexao"))
        {
            using (NpgsqlCommand command = new NpgsqlCommand(valorContSql, conn))
            {
                command.CommandTimeout = 190;
                command.Connection = conn;
                command.CommandText = valorContSql;

                conn.Open();

                using (NpgsqlDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        relcontabil.Add(new RelContabil()
                        {
                            Id = dr.GetInt32(0),
                            RazaoSocial = dr.GetString(1),
                            Exercicio = dr.GetString(2),
                            Lucro = dr.GetDecimal(3)
                        });
                    }
                }
            }
            conn.Close();
        }

        RelatorioContabilDataGridView.DataSource = relcontabil;
        QuantidadeLabel.Text = relcontabil.Count.ToString();
    }
    catch (NpgsqlException nex)
    {
        //tratar ?!
    }
}
    
14.06.2018 / 19:32
1

The following code (.NET Framework version: 4.6.1)

DataTable dt = new DataTable();
dt.Columns.Add("Valor formatado");

dt.Rows.Add(new object[] { string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", 2.1m) });
dt.Rows.Add(new object[] { string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", 2.2m) });
dt.Rows.Add(new object[] { string.Format(CultureInfo.GetCultureInfo("pt-BR"), "{0:C}", 2.3m) });

dataGridView1.DataSource = dt;

Result:

    
14.06.2018 / 19:09