segunda-feira, 29 de março de 2021

Formatar TextBox Valores Decimais

 Adicione um TextBox ao seu projeto e faça as seguintes alterações:

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


Nenhum comentário:

Postar um comentário