Reputation: 3616
I've written a check to restrict the user to entering a weight field to no more than one decimal place in a text box.
private void txtWeight_TextChanged(object sender, EventArgs e)
{
decimal enteredWeight;
if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
{
decimal roundedWeight = RoundDown(enteredWeight, 1);
if (enteredWeight != roundedWeight)
{
txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
}
}
}
(the implementation of RoundDown()
is inconsequential)
My problem is that after the user enters a second digit after the decimal point, it removes it fine, but the cursor is moved to the start of the field.
e.g.
before: 69.2|
Then type a 4 (e.g. for 69.24
which is not allowed)
after: |69.2
I'd like the cursor in the text box to remain wherever it was... Can this be done?
Upvotes: 1
Views: 520
Reputation: 36483
Try:
txtWeight.CaretIndex = txtBox.Text.Length;
Or:
txtWeight.SelectionStart = txtBox.Text.Length;
Upvotes: -1
Reputation: 4124
You may save the position of the caret and then re-set it after you have made the text change.
private void txtWeight_TextChanged(object sender, EventArgs e)
{
decimal enteredWeight;
if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
{
decimal roundedWeight = RoundDown(enteredWeight, 1);
if (enteredWeight != roundedWeight)
{
int caretPos = txtWeight.SelectionStart;
txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
txtWeight.SelectionStart = caretPos;
}
}
}
Upvotes: 4