Reputation: 82
I'm currently writing a tiny finance-related application and want to make sure that my users KNOW how to write a decimal value (with a DOT instead of a COMMA.)
To make sure that the input is correct I've submitted the control to the TextChanged event as follows.
// Remove people not knowing how to write decimals.
if (ExpenseValueTB.Text.Contains(',')) {
ExpenseValueTB.Text = ExpenseValueTB.Text.Replace(',', '.');
ExpenseValueTB.Focus();
}
Now this definitely works, but unfortunately the input cursor jumps back to the beginning. So if someone wanted to write '15,96', they end up writing 9615.
I've looked around but any other similar issues were js or PHP
Many thanks!
Upvotes: 1
Views: 1018
Reputation: 66
Is that what are you looking for?
ExpenseValueTB.SelectionStart = ExpenseValueTB.Text.Length;
Upvotes: 1
Reputation: 216293
You could use SelectionStart and SelectionLength from the TextBox base methods
if (ExpenseValueTB.Text.Contains(',')) {
ExpenseValueTB.Text = ExpenseValueTB.Text.Replace(',', '.');
ExpenseValueTB.SelectionStart = ExpenseValueTB.Text.IndexOf('.') + 1;
ExpenseValueTB.SelectionLength = 0;
ExpenseValueTB.Focus();
}
but probably your best approach is to remove the simple TextBox and use a MaskedTextBox that allows you to better format the user input
Upvotes: 3