1

Preciso colocar o texto R$ numa textbox de forma a que fique com o seguinte formato:

R$: 1.200,58

Estou tentando das seguintes formas sem sucesso:

textbox1.Text = Convert.ToDouble(textbox1.Text).ToString("C"); 

e

textbox1.Text = Decimal.Parse(texbox.text).ToString("N2");
1
  • O que acha de usar o evento OnEnter da textbox pra remover o "R$". E o evento OnLeave para colocar de volta?
    – Latrova
    7/08/2014 às 15:38

5 Respostas 5

4

Caso você aceite o uso de eventos, pode usar dessa maneira:

Função para colocar a mascara

    private void RetornarMascara(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        txt.Text = double.Parse(txt.Text).ToString("C2");
    }

Função para retirar a mascara

    private void TirarMascara(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        txt.Text = txt.Text.Replace("R$", "").Trim();
    }

Função para somente permitir números e virgula

    private void ApenasValorNumerico(object sender, KeyPressEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
        {
            if (e.KeyChar == ',')
            {
                e.Handled = (txt.Text.Contains(','));
            }
            else
                e.Handled = true;
        }
    }

Aplica todas as funções aos respectivos eventos

    private void AplicarEventos(TextBox txt)
    {
        txt.Enter += TirarMascara;
        txt.Leave += RetornarMascara;
        txt.KeyPress += ApenasValorNumerico;
    }

Exemplo de uso:

    public Form1()
    {
        InitializeComponent();

        AplicarEventos(textBox1);
        AplicarEventos(textBox2);
    }
1
  • Muito obrigo mesmo por responder, Valeu, fico te devendo mais uma. 9/08/2014 às 13:26
2

Utilizo a função javascript abaixo pra colocar a mascara:

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789\37';
var aux = aux2 = '';
if (!e) e = window.event;
var whichCode = e.which || e.keyCode;
if (isValidKey(whichCode)) return true;
key = String.fromCharCode(whichCode); // Valor para o c¢digo da Chave
if (strCheck.indexOf(key) == -1) return false; // Chave inv lida
len = objTextBox.value.length;
for (i = 0; i < len; i++)
    if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
aux = '';
for (; i < len; i++)
    if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) objTextBox.value = '';
if (len == 1) objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
if (len == 2) objTextBox.value = '0' + SeparadorDecimal + aux;
if (len > 2) 
{
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--) 
    {
        if (j == 3) 
        {
            aux2 += SeparadorMilesimo;
            j = 0;
        }
        aux2 += aux.charAt(i);
        j++;
    }
    objTextBox.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
    objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
}
return false;
}

coloque a chamada no evento onkeypress do seu textbox, return(MascaraMoeda(this,'.',',',event));

Teste e veja se causa o efeito desejado.

ou você pode utilizar alguma biblioteca jquery, exemplo: http://www.fabiobmed.com.br/criando-mascaras-para-moedas-com-jquery/

2
  • Achei método menos complicado obrigo por responder 9/08/2014 às 13:25
  • Por que você acha que uma solução em JS resolve um problema de Windows Forms?
    – Maniero
    25/08/2014 às 1:40
1

Aí @Fabricio é bem simples.

System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
        label.Text = string.Format("{0:C}", Convert.ToDouble(1200.58));

Mas lembre-se tudo vai depender da sua CultureInfo e CultureUi. Se elas estiverem em outra língua, não vai funcionar do jeito que você quer!

1

Crie um textbox com o nome txt_valor e atribua os eventos KeyPress, Leave, KeyUp e uma string valor

string valor;
private void txt_valor_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
    {
        if (e.KeyChar == ',')
        {
            e.Handled = (txt_valor.Text.Contains(","));
        }
        else
            e.Handled = true;
    }            
}

private void txt_valor_Leave(object sender, EventArgs e)
{
    valor = txt_valor.Text.Replace("R$", "");
    txt_valor.Text = string.Format("{0:C}", Convert.ToDouble(valor));
}

private void txt_valor_KeyUp(object sender, KeyEventArgs e)
{
    valor = txt_valor.Text.Replace("R$","").Replace(",","").Replace(" ","").Replace("00,","");
    if(valor.Length == 0)
    {
        txt_valor.Text = "0,00"+valor;
    }
    if(valor.Length == 1)
    {
        txt_valor.Text = "0,0"+valor;
    }
    if(valor.Length == 2)
    {
        txt_valor.Text = "0,"+valor;
    }
    else if(valor.Length >= 3)
    {
        if(txt_valor.Text.StartsWith("0,"))
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",").Replace("0,","");
        }
        else if(txt_valor.Text.Contains("00,"))
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",").Replace("00,","");
        }
        else
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",");
        }
    }           
    valor = txt_valor.Text;
    txt_valor.Text = string.Format("{0:C}", Convert.ToDouble(valor));
    txt_valor.Select(txt_valor.Text.Length,0);
}
0

Quando tenho dúvida sempre aqui encontro soluções que me auxiliam a realizar o que quero.... Por este motivo hoje venho contribuir.

Não sei se é a melhor forma, mas ai vai como utilizo.

Tenho uma classe static chamada uUseful, nela possuo três métodos public.

Método KeyPress (Class cUseful)

public static void DecimalKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {            
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);
            
        if (e.KeyChar == '.')
        {
            if (objTextBox.Text.IndexOf(",") >= 0)
            {
                e.Handled = true;
                return;
            }
            if (objTextBox.Text.Trim().Length < 1)
            {
                e.Handled = true;
                objTextBox.Text = "0,";
                objTextBox.SelectionStart = objTextBox.Text.Length;
                return;
            }
            else
            {
                e.KeyChar = ',';
            }
        }
    }

Método KeyDown (Class cUseful)

public static void DecimalKeyDown(object sender, System.Windows.Forms.KeyEventArgs e, int pNumberDecimalPlaces = 2)
    {
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);

        if (objTextBox.SelectionLength == objTextBox.Text.Length || objTextBox.Text == ("0,").ToString().PadRight(pNumberDecimalPlaces, '0')) objTextBox.Text = "";

        if (e.KeyCode < System.Windows.Forms.Keys.D0 || e.KeyCode > System.Windows.Forms.Keys.D9)
        {
            if (e.KeyCode < System.Windows.Forms.Keys.NumPad0 || e.KeyCode > System.Windows.Forms.Keys.NumPad9)
            {
                if (e.KeyCode != System.Windows.Forms.Keys.Back)
                {
                    if (e.KeyCode == System.Windows.Forms.Keys.Oemcomma || e.KeyCode == System.Windows.Forms.Keys.Decimal || e.KeyCode == System.Windows.Forms.Keys.OemPeriod)
                    {

                        if (objTextBox.Text.IndexOf(",") >= 0) // só permite uma virgula
                        {
                            e.SuppressKeyPress = true;
                            return;
                        }

                        if (objTextBox.Text.Trim().Length < 1) // caso coloque uma virgula sem colocar valor
                        {
                            objTextBox.Text = "0,";
                            e.SuppressKeyPress = true;
                            objTextBox.SelectionStart = objTextBox.Text.Length;
                            return;
                        }

                    }
                    else
                    {
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
                else
                {
                    if (objTextBox.Text == "0,")
                    {
                        objTextBox.Text = "";
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
            }
            else
            {
                if (objTextBox.Text.IndexOf(",") >= 0)
                {
                    if (((System.Convert.ToInt32(objTextBox.Text.IndexOf(",") + 1) - objTextBox.Text.Length) * -1) == pNumberDecimalPlaces)
                    {
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
            }
        }
    }

Método Leave (Class cUseful)

public static void DecimalLeave(object sender, System.EventArgs e, int pNumberDecimalPlaces = 2)
    {
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);

        if (!string.IsNullOrEmpty(objTextBox.Text))
        {
            if (objTextBox.Text.Trim().Length != 0) objTextBox.Text = System.Convert.ToDecimal(objTextBox.Text.Replace(".", ",")).ToString("n2");
            else objTextBox.Text = ("0,").ToString().PadRight(pNumberDecimalPlaces, '0');
        }
        else
        {
            objTextBox.Text = ("0,").ToString().PadRight(pNumberDecimalPlaces, '0');
        }
    }

Já na interface possuo três métodos de direcionamento

Método KeyPress (Form)

private void DecimalKeyPress(object sender, KeyPressEventArgs e)
        {
            BackEnd.cUseful.DecimalKeyPress(sender, e);
        }

Método KeyDown (Form)

private void DecimalKeyDown(object sender, KeyEventArgs e)
        {
            BackEnd.cUseful.DecimalKeyDown(sender, e);
        }

Método Leave (Form)

private void DecimalLeave(object sender, System.EventArgs e)
        {
            BackEnd.cUseful.DecimalLeave(sender, e);
        }

Por fim, inicio a propriedade Text dos objectos TextBox com o valor "0,00" e vou aos métodos KeyPress, KeyDown e Leave e seleciono os métodos privados criados no (Form).

Att. Ingeniero de software en América Latina Robson Knevitz

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .