2012-10-12 30 views
0

我已經爲使用C#.NET的Windows應用程序創建了自定義文本框。它必須接受小數點(浮點數),如8.32和16.002。在C#.NET中接受十進制的自定義文本框

我已經構建了以下算法。它只接受純數字。我無法弄清楚如何使它接受浮動。

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Drawing; 
using System.Data; 
using System.Text; 
using System.Windows.Forms; 

namespace SmartTextBoxLib 
{ 
    public partial class SmartTextBox : TextBox 
    { 
     public SmartTextBox() 
     { 
      InitializeComponent(); 
     } 
     protected override void OnKeyPress(KeyPressEventArgs e) 
     { 
      if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) 
      { 
       e.Handled = true; 
      } 
      base.OnKeyPress(e); 
     } 
    } 
} 
+0

'OnKeyPress'是錯誤的事件使用。如果有人用鼠標在文本框中粘貼文本會怎麼樣?你應該簡單地使用其中一個現有的蒙面文本框。 –

+0

我知道Masked Text-Boxes的存在。我只是試圖爲了學習而重新發明輪子。所以,如果你能建議任何替代解決方案,將不勝感激。 –

回答

1

您可以使用:

if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
    e.Handled = true; 
base.OnKeyPress(e); 

這使得數字字符或.。 如果你用它來分隔小數,你可以使它成爲,


或者,你可以這樣做:

decimal value; 
e.Handled = !decimal.TryParse((sender as TextBox).Text + e.KeyChar, out value); 
base.OnKeyPress(e); 
+1

那麼'21.47..1.5..'是一個有效的數字? –

+0

謝謝。稍微修改一下像OnTextChanged事件修改,我終於可以使它工作,並將像21.47..1.5 ..這樣的數字定義爲無效。 –

+1

@Samik:增加了一個替代品。 –

1

使用

System.Windows.Forms.NumericUpDown 

相反,它會爲你做到這一點。

+0

並呼叫什麼事件?或者檢查一下情況? –

+0

@Samik:它有一個名爲Value的Decimal屬性。 –

+0

我明白了。但是如果我想將TextBox的行爲修改爲接受小數,我應該如何重寫我的算法? –

0

您可以使用MaskedTextBox代替Texbox控制。

定義上MaskedTextBox控件Mask屬性:

maskedTextBoxInstance.Mask = "99.000"; 
相關問題