2010-10-05 74 views
3

我注意到,当我在C#应用程序中请求NumericUpDown控件的Value时,插入符号被重置为位置0.这很烦人,因为我的应用程序会周期性地获取控件的值,所以如果发生这种情况时用户正在输入它,插入符号意外移动,混淆了他们的输入。获取NumericUpDown的值可以移动插入位置,我可以阻止它吗?

有没有办法来防止这种情况或解决方法?它似乎没有SelectionStart属性,否则我可以让轮询过程保存插入位置,获取值,然后将其设置为一个体面的解决方法。

+1

我不能重复这个。我有一个计时器,每3秒获取一个值并将标签控制文本设置为该值。如果我在输入值时打字,则标签会发生变化,但插入符号不会发生任何变化。插入符号重置为开始的唯一时间是数值大于最大设置值(此时该值也设置为最大值)。 – keyboardP 2010-10-05 16:46:22

+0

嗯......似乎只发生格式化事件发生。例如,如果将DecimalPlaces设置为2,则插入符将重置,如果字段中的字符串为“36.1”,但不是字符串为“36.10”,并且正在键入值的整数部分... – bobulous 2010-10-05 17:15:36

回答

3

我可以用小数点重现错误。在你的计时器滴答事件(或无论你在拉动价值),尝试添加以下代码:

numericUpDown1.DecimalPlaces = 2; 

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

你不能得到SelectionStart,但如果从当前字符串的结尾选择和设定将selection length设置为0,则应该将插入符号放在正确的位置。

+0

很好的解决方法,谢谢 – bobulous 2010-10-05 18:36:32

2

插入键会使文本中的键入和光标变得混乱,因为使值变成插入符号的位置。因此,获得textboxbase并自行设定脱字符号的价值的解决方案。

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) 
     { 

     } 
    } 
+0

Afternote:所以,解决方案是从Numericupdown获取私有TextBoxBase。此外,我有一个数据绑定的NumericUpdown。 WriteValue将插入的位置弄乱,因为它获取值并将其放入数据源中。所以,我通过在获取价值之前获得插入位置来解决这个问题,并在之后进行修复。 – 2012-03-09 13:32:59

相关问题