using System.Runtime.InteropServices;[DllImport("User32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("User32.dll")] static extern int GetWindowLong(IntPtr hWnd, int nIndex); public const int GWL_STYLE = -16; public const int ES_NUMBER = 0x2000; private void Form1_Load(object sender, EventArgs e) { SetWindowLong(textBox1.Handle, GWL_STYLE, GetWindowLong(textBox1.Handle, GWL_STYLE) | ES_NUMBER); }
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("User32.dll")]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public const int GWL_STYLE = -16;
public const int ES_NUMBER = 0x2000;
private void Form1_Load(object sender, EventArgs e)
{
SetWindowLong(textBox1.Handle, GWL_STYLE,
GetWindowLong(textBox1.Handle, GWL_STYLE) | ES_NUMBER);
}
{
e.Handled = ("0123456789" + (char)8 + (char)13).IndexOf(e.KeyChar) < 0;
}这样现在不了粘贴
除非在TextChange事件中再处理一下
{
if ((short)e.KeyChar >= 48 && (short)e.KeyChar <= 57 || (short)e.KeyChar == 8)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
两个简单的方法:
1:使用EditeMask空间,设置为只能输入数字
2:用char.IsNumber()函数来判读输入的每个字符是不是数字就行了。
OK!
{
textBox1.Text = Regex.Replace(textBox1.Text, @"[^0-90-9]", "");
}否则这样试下private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = Regex.Replace(textBox1.Text, @"[^0-9]", "");
}
我试的好像不行啊asp我知道可以 winform真的可以吗
{
string regstr = @"^-?\d+$";//整数,包括全角
Regex regex = new Regex(regstr);
string text = textBox1.Text;
if (regex.IsMatch(text))
{
MessageBox.Show("ok");
}
else
{
MessageBox.Show("only can input number");
}
}
catch(Exception e)
{
MessageBox.show("输入的不是数字!");
textbox1.Text="";
}
方法2。 用正则表达式
ok
多谢了 哈
不过有一个缺点,就是输入错误的焦点在顶部
textBox1.SelectionStart = textBox1.Text.Length;这个是指定到尾部,当然,如果是在中间插入的话,还是有缺点,虽然也可以做到,但是没那个必要的
明白了 谢谢了
看来自己的基础真的很差 哈哈
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;namespace OperateSQL
{
class MyTextBox:TextBox
{
private bool _isNum = false; public bool IsNum
{
get { return _isNum; }
set { _isNum = value; }
} protected override void OnKeyPress(KeyPressEventArgs e)
{
if (_isNum)
{
if (e.KeyChar < '0' || e.KeyChar > '9')
{
e.Handled = true;
}
else
{
base.OnKeyPress(e);
}
}
}
}
}用的时候把IsNum属性设为true就行了