小弟最近開始在寫WinForm的程式...想做一個只能輸入數值的Textbox
讓使用者只能輸入數值...小弟去找了一下資料...做了一個demo.介紹如何達到此功能...
WinForm(c#)
.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form7 : Form { public Form7() { InitializeComponent(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) { e.Handled = true; } } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(this.textBox1.Text); } } }
執行結果:
如果想把此textbox做成一個元件,可以繼承textbox,並且改寫OnKeyPress事件,以後就可以拉此元作重覆使用了
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; namespace NumbersTextbox { public class NumbersTextbox : TextBox { protected override void OnKeyPress(KeyPressEventArgs e) { base.OnKeyPress(e); if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) { e.Handled = true; } } } }
參考網址:
http://www.csharphelp.com/board2/read.html?f=1&i=58437&t=47961
# re: [WinForm]利用C#做一個只可以輸入數值的Textbox(Only numbers Textbox), Posted by 杜B on 2008/6/29 上午 03:43 回覆
似乎沒有做 copy and paste 的控制...
# re: [WinForm]利用C#做一個只可以輸入數值的Textbox(Only numbers Textbox), Posted by chhuang on 2008/6/29 下午 08:38 回覆
private bool IsBlocked; to puma: private void textBox1_KeyPress(object sender, KeyPressEventArgs e){ if (IsBlocked) e.Handled = true; if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 3 || e.KeyChar == 8 || e.KeyChar == 22) { return; } e.Handled = true;} private void textBox1_KeyDown(object sender, KeyEventArgs e){ IsBlocked = false; if (e.Control && e.KeyCode == Keys.V) { string s = Clipboard.GetText(); if ( string.IsNullOrEmpty(s) || Regex.Match(s, @"\D").Success) { IsBlocked = true; } }}
# re: [WinForm]利用C#做一個只可以輸入數值的Textbox(Only numbers Textbox), Posted by Hei on 2008/7/6 下午 11:43 回覆
可以轉.NET 2.0的話, 可以試下masked textbox, 效果應該會比較好
# re: [WinForm]利用C#做一個只可以輸入數值的Textbox(Only numbers Textbox), Posted by Adolph on 2008/7/16 下午 06:14 回覆
應該不用那麼麻煩吧 好像用規則運算式就可以達到了