C#中限定文本框中输入数据并要求

作者&投稿:类玛 (若有异议请与网页底部的电邮联系)
C#里,怎么限制文本框的输入内容~

用textBox1.maxLength属性设置

限制文本框,只能输入0-9 a-z
这个可以写在文本框的keypress事件中
if(!char.IsLetterorDigit(e.KeyChar))
{
MessageBox.Show("Wrong");
e.Handled=true;
}
至於复制 粘贴 应该是去判断Clipboard获取的对象是否符合以上(0-9 a-z等)条件,如果符合就
可执行粘贴的动作,否则不执行(未验证)

下面是我写的一个只能输入数字的文本框的控件。你可能用的到。
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;

namespace DataManageModule.Common
{
/// <summary>
/// 只能输入数字的文本框:TextBox
/// 说明:该文本框除了0~9、一个小数据点,上下左右键、删除键(Delete)、BackSpace键 能输入外其它的都不能输入
/// </summary>
public class NumberTextBox : TextBox
{
private ToolTip toolTip;//当输入非数字字符时,弹出的汽泡提示框
private System.ComponentModel.IContainer components;//系统本身
protected bool isAllowKeyPress;//是否允许按銉

private double maxValue = double.MaxValue;
[Description("输入数字的最大值")]
public double MaxValue
{
get { return maxValue; }
set { maxValue = value; }
}
private double minValue = double.MinValue;
[Description("输入数字的最小值")]
public double MinValue
{
get { return minValue; }
set { minValue = value; }
}

private bool isNegativeEnable = true;
/// <summary>
/// 是否允许为负数
/// </summary>
[Description("是否允许为负数:如果为Ture则可以为负数,否则只能是正数")]
public bool IsNegativeEnable
{
get { return isNegativeEnable; }
set { isNegativeEnable = value; }
}

/// <summary>
/// 构造函数,并初化值为0
/// </summary>
public NumberTextBox()
{
InitializeComponent();
this.Text = "0";
this.TextChanged += new EventHandler(NumberTextBox_TextChanged);
}

void NumberTextBox_TextChanged(object sender, EventArgs e)
{
double value;
if (this.Text == "" || this.Text=="-" || this.Text =="-0" || this.Text =="-0.")
{
return;
}
try
{
value = Convert.ToDouble(this.Text.Trim());
}
catch
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据错误!", this, 1000);
this.Text = "0";
return;
}
if (value > maxValue || value < minValue)
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据超出范围!", this, 1000);
this.Text = minValue.ToString();
return;
}
if (isNegativeEnable)
{

}
else
{
if (value < 0)
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据错误!", this, 1000);
this.Text = "0";
return;
}
}
}
/// <summary>
/// 重写OnKeyPress事件
/// </summary>
/// <param name="e"></param>
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (isAllowKeyPress)//如果允许
{
e.Handled = true;
}
base.OnKeyPress(e);
}

protected override void OnLeave(EventArgs e)
{
if (this.Text.ToString().Trim() == "" || this.Text == "." || this.Text == "-"||this.Text=="-0" || this.Text=="-0.0" || this.Text=="-0")
{
this.Text = "0";

}
if (this.Text.ToString().IndexOf('.') == 0 && this.Text.Length > 1)
{
this.Text = "0" + this.Text;
}

if (this.Text.Trim().IndexOf("-.") != -1 && this.Text.Length > 3)
{
this.Text = this.Text.Insert(1, "0");
}
double value;
try
{
value = Convert.ToDouble(this.Text.Trim());
this.Text = value.ToString();
}
catch
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据错误!", this, 1000);
this.Text = "0";
return;
}
if (value > maxValue || value < minValue)
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据超出范围!", this, 1000);
this.Text = "0";
return;
}
if (isNegativeEnable)
{

}
else
{
if (value < 0)
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("数据错误!", this, 1000);
this.Text = "0";
return;
}
}
base.OnLeave(e);
}

protected override void OnKeyDown(KeyEventArgs e)
{

Rectangle rct = new Rectangle(new Point(0,0), new Size(this.Width, this.Height));
Point pt = PointToClient(Cursor.Position);
if (e.KeyValue.Equals(18) || (e.KeyValue >= 112 && e.KeyValue <= 123) || e.KeyValue == 145 || e.KeyValue == 45 || e.KeyValue == 36 || e.KeyValue == 33 || e.KeyValue == 34 || e.KeyValue == 16 || e.KeyValue == 20)
{
isAllowKeyPress = false;
return;
}
if (rct.Contains(pt))
{
Point p=PointToScreen(new Point(0,0));
Cursor.Position = new Point(p.X + this.Width + 1, p.Y + this.Height + 1);
}
if (e.KeyValue.Equals(46) || e.KeyValue.Equals(8) || e.KeyValue.Equals(39) || e.KeyValue.Equals(37) || e.KeyValue.Equals(38) || e.KeyValue.Equals(40))
{
isAllowKeyPress = false;
return;
}
else if ((e.KeyValue == 189) || (e.KeyValue == 109))
{
if (IsNegativeEnable)
{
if (this.Text == "")
{
isAllowKeyPress = false;
return;
}
else
{
int i = this.Text.ToString().IndexOf('-');
if (i != -1)
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("已经存在负号了!", this, 1000);
isAllowKeyPress = true;
return;
}
else
{
isAllowKeyPress = false;
return;
}
}
}
else
{
isAllowKeyPress = true;
}

}
else if ((e.KeyValue == 46) || (e.KeyValue >= 96 && e.KeyValue <= 105) || (e.KeyValue.Equals(110)) || (e.Control == true) || (e.Control == true && (e.KeyValue.Equals(67) || e.KeyValue.Equals(86))) || (e.KeyValue == 8 || (e.KeyValue >= 48 && e.KeyValue <= 57)) || (e.KeyValue.Equals(8)) || (e.KeyValue.Equals(190)) || (e.KeyValue.Equals(13)))
{
string ss = this.Text;
int i = this.SelectionStart;
int j = this.Text.ToString().IndexOf('-');
int k = this.SelectedText.Length;
if (i == 0 && j!=-1 && k==0)
{
if (!(e.KeyValue.Equals(39) || e.KeyValue.Equals(40)))
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("不应该在负号前输入数字!.", this, 1000);
}
isAllowKeyPress = true;
}
else
{
isAllowKeyPress = false;
}
}
else
{
isAllowKeyPress = true;
this.toolTip.Show("", this, 0);
this.toolTip.Show("只能输入数字!", this, 1000);
}
if ((e.KeyValue.Equals(190) || e.KeyValue.Equals(110)))
{
int i=this.Text.ToString().IndexOf('.');
if (i == -1)
{
isAllowKeyPress = false;
return;
}
else
{
this.toolTip.Show("", this, 0);
this.toolTip.Show("已经存在小数点了!", this, 1000);
isAllowKeyPress = true;
return;
}
//i = this.SelectionStart;
//int j = this.Text.ToString().IndexOf('-');
//if (i == 0 && j != -1)
//{
// if (!(e.KeyValue.Equals(39) || e.KeyValue.Equals(40)))
// {
// this.toolTip.Show("", this, 0);
// this.toolTip.Show("不应该在负号前输入数字!.", this, 1000);
// }
// isAllowKeyPress = true;
// return;
//}
//else
//{
// isAllowKeyPress = false;
// return;
//}
}
base.OnKeyDown(e);
this.Refresh();
}

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.toolTip.IsBalloon = true;
this.SuspendLayout();
//
// toolTip
//
this.toolTip.AutomaticDelay = 50;
this.toolTip.AutoPopDelay = 500;
this.toolTip.BackColor = System.Drawing.Color.White;
this.toolTip.ForeColor = System.Drawing.Color.Black;
this.toolTip.InitialDelay = 100;
this.toolTip.ReshowDelay = 0;
this.toolTip.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Error;
this.toolTip.ToolTipTitle = "错误";
this.ResumeLayout(false);

}
}

}

来一个简单的,只能输入0~9,小数点,空格,退格。

public class MyTextBox : TextBox
{
const int WM_CHAR = 0x0102;
const int VK_BACK = 0x08;
const int VK_SPACE = 0x20;

protected override void WndProc(ref Message m)
{
if (m.Msg == WM_CHAR && m.WParam.ToInt32() != '.' && (m.WParam.ToInt32() < '0' || m.WParam.ToInt32() > '9') && m.WParam.ToInt32() != VK_BACK && m.WParam.ToInt32() != VK_SPACE)
{
return;
}
base.WndProc(ref m);
}
}


思茅市18131208387: C#里,怎么限制文本框的输入内容 -
马该天晴: 验证控件或者用正则表达式来限制输入字符的格式吧,网上search一下,N多.

思茅市18131208387: C# 如何限制文本框职能输入数字 -
马该天晴: /// <summary> /// 屏蔽非数字键 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtDateFrom_KeyPress(object sender, KeyPressEventArgs e) { //---------------[变数声明]------------------- //-------------...

思茅市18131208387: C# winform 程序中如何限制一个文本框中只输入数字和字母呢? -
马该天晴: private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e){if((e.KeyChar>='0'&&e.KeyChar<='9')||(e.KeyChar>='A'&&e.KeyChar<='Z')||(e.KeyChar>='a'&&e.KeyChar<='z'))e.Handled=false;elsee.Handled=true;}

思茅市18131208387: 在C#中用什么方法使窗口文本框内只能输入数字?
马该天晴: 方案1: 可以使用掩码文本框. 方案2: 可以在文本框的onkeydown事件中用 "正则表达式" 进行验证.

思茅市18131208387: C# .net中有一个文本框,要求只能输入数字,同时这个文本框可以空着 -
马该天晴: Winform的(C#)来实现限制文本框只能输入数字,一般的做法是价值的一个关键事件?:判断keychar.只限于几个键来输入数字,小数点,退格键,删除. 数字0到9的相应keychar 48至57,小数点是46,退格键是8,的小数点为46.2.输...

思茅市18131208387: C#中如何限制textbox只能输入英文和数字 -
马该天晴: 可以在文本框的按健事件中判断当前按的是什么键 ,CHAR本身也提供了判断是字符还是数字的方法. 基本代码如下.添加文本框按钮事件处理. private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) || !char.IsLetter(e.KeyChar))//如果不是字符 也不是数字 {e.Handled=true; //当前输入处理置为已处理.即文本框不再显示当前按键信息 } }

思茅市18131208387: C#中如何设定textbox中只能输入数字? -
马该天晴: 使用验证控件. 自定义空间里面写正则表达式 C#中验证 public static bool ifNumber(object sNum, out long outint){if (sNum == null){outint = 0;return false;}if (long.TryParse(sNum.ToString(), out outint))return true;elsereturn false;}推荐不这样用.此为服务器端

思茅市18131208387: c#中,一个textbox,怎样要求这个文本框中只能输整数,除整数其他不行 -
马该天晴: 调用TextBox的KeyPress事件,也就是每次键盘输入都进行if判断private void txtbox_KeyPress(object sender, KeyPressEventArgs e){ //如果输入的不是数字键,也不是回车键、Backspace键,则取消该输入 if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar!=(char)13 && e.KeyChar!=(char)8) { e.Handled = true; } }

思茅市18131208387: c#中怎么让文本框只能输入数字 -
马该天晴: 在Web程序中可以用Validator进行验证,而在桌面应用程序中,可以利用文本框的textchanged事件进行验证,验证方法一般是采用正则表达式

思茅市18131208387: C#怎么在textBox中限制只能输入整数,并且限制输入的长度 -
马该天晴: @"^\-?[0-9]+$"用正则表达式验证就ok了

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网