2017-12-08 7 views
0

自分のアプリケーションでnumericupdownコントロールを使用したいと思います。代わりにプレーンテキストボックスを使用できることはよく知っていますが、私はこの特定のコントロールのUIが私のアプリケーションでやっているものと似ているのが好きです。Padleft on numericupdown

また、必要なテキスト出力ごとに、左側に0が必要です。私が間違っていない場合、これは標準的な数値制御ではサポートされていません。長さは4桁を超えてはなりません。しかし、もっと入力した場合は、新しいキーストロークが優先され、左端の数字がドロップされるようにする必要があります。上向き矢印と下向き矢印は、通常の動作ごとに値を増減します。値をキー入力した後でも。

マイナスにすることは許されません。全体の整数だけを受け入れる必要があります。しかしこれは在庫機能によって容易に処理されます。

+0

[codereview.stackexchange.com](https://codereview.stackexchange.com)には現在の形式の質問が適しています。あなたがstackoverflowでそれを保持したい場合は、投稿を編集し、質問をして、あなた自身の答えを投稿してください。そうすれば、フィーチャ・リーダにとってより有用になるでしょう。 –

+0

codereviewについて知りませんでした。それに言及してくれてありがとう。私は先に進み、それをやります。 –

答えて

0

次の人のために部分的に回答を投稿します。私がばかではないという保証を部分的に探しています。

このハックは、最終値を抽出する前に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 
    } 
} 
関連する問題