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?
Asked
Active
Viewed 627 times
0
-
you need textbox focus leave event then loop over length of text to insert ',' in it. – sharafjaffri Oct 16 '12 at 07:15
-
I have tried SelectionChanged, gives me an error – Hendra Anggrian Oct 16 '12 at 07:18
-
I also have tried converting String to Char and manually put the "," – Hendra Anggrian Oct 16 '12 at 07:19
3 Answers
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);
}
}

Gianni B.
- 2,691
- 18
- 31
-
And [another good answer](http://stackoverflow.com/a/12492634/1498857) by Marc Gravell – Gianni B. Oct 16 '12 at 07:24
-
-
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;
}
}

Ashton D'Sa
- 31
- 7
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
-
works on 1000 to 1,000. doesn't work on a lot amount of digits – Hendra Anggrian Oct 16 '12 at 09:54