Mask CURRENCY {en-BR} in Gridview C#

Asked

Viewed 1,554 times

1

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

I’m using the CultureInfo.CurrentCulture, but when I put to turn, in the GridView only the first Line(Row) appears the mask and not in 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:\00\.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);
        }
    }
}

2 answers

2


The First problem is that you are using RowCount and not .Rows.Count in this way he is only going through the lines that are being displayed and not all the lines of the collection. But this is also not how you format the column.

To format, simply define the DefaultCellStyle:

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

But for this, the object property has to be numerical (decimal).

Class must be 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 solve them, but I leave here how would 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 ?!
    }
}
  • thanks for your help. .

  • Suggested edition: SOLUTION I used the same code, but I made small changes, below. ; decimal MoedaFormat;&#xA;&#xA; for (int i = 0; i < RelatorioContabilDataGridView.Rows.Count; i++)&#xA; {&#xA; MoedaFormat = Decimal.Parse(RelatorioContabilDataGridView.Rows[i].Cells[2].Value.ToString());&#xA; var lucroCampo = RelatorioContabilDataGridView.Rows[i].Cells[2].Value = MoedaFormat.ToString("C2", CultureInfo.CurrentCulture);&#xA; RelatorioContabilDataGridView.Rows[i].Cells[2].Value = lucroCampo.ToString();&#xA; }

  • you kept your code, and only changed the .Rows.Count ? @Andre

  • I was making two conversions on the line where the mask is implanted, so he was giving conflict. I created the'lucroCampo' variable to receive the value with the mask, then I returned it as a string in the Grid. OBS: I didn’t test with Rowcount, I switched to Rows.Count and so I kept it.

  • you have any idea that this pile of for is totally unnecessary ?

  • In a way yes, but it’s my first haha weight code. This experience will help me create more objective and level-free codes Mcgyver haha

  • because then...this is very wrong... anyway the right code is up there, I don’t even want to think about how many records are returned in your query and the so much of loop that will be done literally for no reason

  • I will start posting more often here, I will improve my codes. I appreciate the help and also the advice. Hug.

Show 3 more comments

1

Following is code: (Version . NET Framework: 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;

Upshot:

inserir a descrição da imagem aqui

  • I get it, I’m gonna try this format.

Browser other questions tagged

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