数字下载时的Padleft

时间:2017-12-08 02:30:17

标签: c# winforms numericupdown

我想在我的应用程序上使用numericupdown控件。我很清楚我可以使用纯文本框,但我更喜欢这个特定控件的UI与我在我的应用程序中所做的一致。

每个所需的文本输出,左边还需要0。如果我没有弄错的话,标准的numericupdown控件不支持。它的长度不应超过4位。但是,如果我输入更多,它必须显示新的击键,并删除最左边的数字。向上和向下箭头应按常规行为递增/递减值。甚至在键入值之后。

永远不应允许它运行否定。它应该只接受整数。但这很容易通过库存功能来处理。

1 个答案:

答案 0 :(得分:0)

部分发布可能跟随的其他人的答案。部分地寻找保证我不是白痴。

请注意,此hack依赖于在提取最终值之前触发Sync()。计时器会很快启动,但不保证事情会以正确的顺序发生。在提取值之前立即手动触发Sync()可能没什么坏处。

public class UpDownWith0 : System.Windows.Forms.NumericUpDown
{

  private System.Windows.Forms.Timer addzeros = new System.Windows.Forms.Timer();

  public UpDownWith0()
  {
    this.addzeros.Interval = 500; //Set delay to allow multiple keystrokes before we start doing things
    this.addzeros.Stop();
    this.addzeros.Tick += new System.EventHandler(this.Sync);
  }

  protected override void OnTextBoxTextChanged(object source, System.EventArgs e)
  {
    this.addzeros.Stop(); //reset the elapsed time every time the event fires, handles multiple quick proximity changes as if they were one
    this.addzeros.Start();
  }

  public void Sync(object sender, System.EventArgs e)
  {
    int val;
    this.addzeros.Stop();
    if (this.Text.Length > 4)
    {
      //I never want to allow input over 4 digits in length. Chop off leftmost values accordingly
      this.Text = this.Text.Remove(0, this.Text.Length - 4);
    }
    int.TryParse(this.Text, out val); //could use Value = int.Parse() here if you preferred to catch the exceptions. I don't.
    if (val > this.Maximum) { val = (int)this.Maximum; }
    else if (val < this.Minimum) { val = (int)this.Minimum; }
    this.Value = val; //Now we can update the value so that up/down buttons work right if we go back to using those instead of keying in input

    this.Text = val.ToString().PadLeft(4, '0'); //IE: display will show 0014 instead of 14
    this.Select(4, 0); //put cursor at end of string, otherwise it moves to the front. Typing more values after the timer fires causes them to insert at the wrong place
  }
}