简体   繁体   中英

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.

eg

before: 69.2|

Then type a 4 (eg 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?

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;
        }
    }
}

加:

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

Try:

txtWeight.CaretIndex = txtBox.Text.Length;

Or:

txtWeight.SelectionStart = txtBox.Text.Length;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM