komodosp
komodosp

Reputation: 3616

Modify text box without moving cursor

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

Answers (3)

Hatted Rooster
Hatted Rooster

Reputation: 36483

Try:

txtWeight.CaretIndex = txtBox.Text.Length;

Or:

txtWeight.SelectionStart = txtBox.Text.Length;

Upvotes: -1

Anders Carstensen
Anders Carstensen

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

David P
David P

Reputation: 2093

Add:

txtWeight.Select(txtWeight.Text.Length - 1,0)

Upvotes: 0

Related Questions