Reputation: 43
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.
Upvotes: 4
Views: 3622
Reputation: 21
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)
{
}
}
Upvotes: 2
Reputation: 69362
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.
Upvotes: 3