0

I'm making a TextBox that urge an input of amount of money. So when users type 1000 in that TextBox it will automatically become 1,000 in the TextBox. Is this possible?

Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97

3 Answers3

2

I don't like the lenght based solution (you need to implement more code for bigger number).

One solution found on google is that:

On XAML file:

<code>
<textbox x:name="PurchasePriceTextBox" text="$0.00" keydown="CurrencyTextBox_KeyDown" lostfocus="CurrencyTextBox_LostFocus" />
</code>

On CS file:

private void CurrencyTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
{
char key = Convert.ToChar(e.Key);
//if the key is not 0-9 prevent the event from being handled further
if (!(key >= '0' && key <= '9'))
   e.Handled = true;  
}
private void CurrencyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
   var textBox = (TextBox)sender;
   decimal value = 0;
   //if the textbox is not already formatted as currency, format it
   if(Decimal.TryParse(textBox.Text.Trim(), NumberStyles.Number | NumberStyles.AllowCurrencySymbol, CultureInfo.CurrentUICulture, out value))
   {
      textBox.Text = string.Format("{0:C}", value);
   }
}

Source

Gianni B.
  • 2,691
  • 18
  • 31
0

Make use of the textbox_TextChanged event of the text box as shown below:

private void textbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (textbox.Text.Length ==4)
        {
            textbox.Text = textbox.Text.Insert(1, ",");
            return;
        }        
    }
0

On Focus Leave event just loop according to your length:

if (textbox.Text.Length <4)
{
    return;
}
int i = 2;
if textbox.Text.Length%2 ==0)
{
    i = 1;
}
l = textbox.Text.Length;
while(l > 3)
{
    textbox.Text = textbox.Text.Insert(i, ",");
    i+=2;
    l-=2;
}
return;
sharafjaffri
  • 2,134
  • 3
  • 30
  • 47