Coin style in a Textbox in Winforms

Asked

Viewed 13,026 times

1

I need to put the text R$ in a textbox so that it has the following format:

R$: 1,200.58

I am trying in the following ways without success:

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

and

textbox1.Text = Decimal.Parse(texbox.text).ToString("N2");
  • How do you feel about using the event OnEnter from the textbox to remove the "R$". And the event OnLeave to put back?

5 answers

4

If you accept the use of events, you can use it this way:

Function to put the mask

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

Function to remove the mask

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

Function to only allow numbers and comma

    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;
        }
    }

Apply all functions to the respective events

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

Example of use:

    public Form1()
    {
        InitializeComponent();

        AplicarEventos(textBox1);
        AplicarEventos(textBox2);
    }
  • Thank you very much for answering, Thanks, I owe you one more.

2

I use the javascript function below to put the mask:

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;
}

place the call in your textbox’s onkeypress event, Return(Mascaramoeda(this,'. ',','));

Test and see if it causes the desired effect.

or you can use some jquery library, example: http://www.fabiobmed.com.br/criando-mascaras-para-moedas-com-jquery/

  • I found less complicated method I force to answer

  • Why You Think A JS Solution Solves a Windows Forms Problem?

1


There @Fabricio is very simple.

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

But remember everything will depend on your CultureInfo and CultureUi. If they’re in another language, it won’t work the way you want it to!

1

Create a textbox with the name txt_valor and assign the events KeyPress, Leave, KeyUp and a string value

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

When I always have doubts here I find solutions that help me to accomplish what I want.... For this reason today I come to contribute.

I don’t know if it’s the best way, but here’s how I use it.

I have a Static class called uUseful, in which I have three public methods.

Keypress method (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 = ',';
            }
        }
    }

Keydown method (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;
                    }
                }
            }
        }
    }

Leave method (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');
        }
    }

Already in the interface I have three methods of directing

Keypress Method (Form)

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

Keydown Method (Form)

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

Leave Method (Form)

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

Finally, I start the Text property of Textbox objects with the value "0.00" and go to the Keypress, Keydown and Leave methods and select the private methods created on (Form).

Att. Software systems in Latin America Robson Knevitz

Browser other questions tagged

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