Question

I've noticed that when I request the Value of a NumericUpDown control in a C# app, the caret is reset to position 0. This is annoying because my app is periodically grabbing the value of the control, so if this happens while a user is typing into it the caret unexpectedly moves, messing with their input.

Is there a way to prevent this, or a workaround? It doesn't seem to have a SelectionStart property, otherwise I could have the polling process save the caret position, get the value, then set it back as a decent workaround.

Was it helpful?

Solution

I can reproduce the error with the decimal point. In your timer tick event (or wherever you're pulling in the value), try adding this code:

numericUpDown1.DecimalPlaces = 2;

numericUpDown1.Select(numericUpDown1.Value.ToString().Length, 0);

You can't get the SelectionStart, but if you select from the end of the current string and set the selection length to 0, it should keep the caret in the correct place.

OTHER TIPS

Intervening key up messes up the typing and the cursor in the text, as getting the value messes up the caret position. Hence the iffy solution of getting the textboxbase and setting the value of the caret ourselves.

    private void numericUpDown_KeyUp(object sender, KeyEventArgs e)
    {
        try
        {
            NumericUpDown numericUpDownsender = (sender as NumericUpDown);

            TextBoxBase txtBase = numericUpDownsender.Controls[1] as TextBoxBase;
            int currentCaretPosition = txtBase.SelectionStart;
            numericUpDownsender.DataBindings[0].WriteValue();
            txtBase.SelectionStart = currentCaretPosition;
        }
        catch (Exception ex)
        {

        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top