Oi pessoal, estou com dificuldades em colocar uma mascara para meu textbox de porcentagem, alguém poderia me ajudar? Estou desenvolvendo em Windows Forms c#.
Abaixo segue a mascara que fiz para textbox de dinheiro, mas não consegui adaptar
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);
}