2015-01-05 79 views
0

之間輸入號碼,我怎樣才能限制進入任何東西,在文本框中99.99如何只允許0-99.99

我的代碼似乎是工作的用戶,比0之間的值,但其他的,它會允許輸入任意號碼。它只允許一次數字和一個點。但它仍然會允許的值大於99.99

下面我的代碼更大:

private void InputMargin_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     try 
     { 
      // allow only number and dot 
      if ( ! char.IsControl(e.KeyChar) 
       && ! char.IsDigit(e.KeyChar) 
       && e.KeyChar != '.' 
       || (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
      ) 
      { 
       //e.Handled = true; 
       double margin; 
       double.TryParse((sender as TextBox).Text, out margin); 

       if (margin >= 0 && margin <= 99.99) 
       { 
        e.Handled = true; 
       } 
       else 
       { 
        e.Handled = false; 
       } 
      } 

     } 
     catch 
     { 
      e.Handled = false; 
     } 
    } 
+0

爲什麼你不應該使用蒙面文本框? –

+0

爲什麼不試試像這樣的'[0-9] {1,2} [。] {0,1} [0-9] {2}''的正則表達式。這可能不是正確的選擇,但可以作爲出發點 – Saravanan

回答

0

爲什麼不使用NumericUpDown控件與小數位數屬性設置爲2

無需添加任何額外的編碼像文本框。

0

你爲什麼用'& & e.KeyChar!='。'因爲這樣做不接受'。' .just刪除這個,因爲你也使用(發件人爲文本框).Text.IndexOf('。')> -1這隻接受一個'。'在整個文本字段中,所以Right if語句將會如此。

if ( ! char.IsControl(e.KeyChar) 
       && ! char.IsDigit(e.KeyChar) 
       || (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
      ) 
    { 
//Your Code 
}