小弟最近開始在寫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; } } } }
沒有留言:
張貼留言