
c#怎么能text只允许输入数字
RTif(e.KeyValue>=48&&e.KeyValue<=57){e.KeyData=Keys.D0;}...
RTif (e.KeyValue >= 48 && e.KeyValue <=57)
{
e.KeyData = Keys.D0;
} 展开
{
e.KeyData = Keys.D0;
} 展开
6个回答
展开全部
1.在Winform(C#)中要实现限制Textbox只能输入数字,一般的做法就是在按键事件中处理,
判断keychar的值。限制只能输入数字,小数点,Backspace,del这几个键。数字0~9所
对应的keychar为48~57,小数点是46,Backspace是8,小数点是46。
2.输入小数点。输入的小数要符合数字的格式,类似9.9.9这样的是不能够输入的。做法就是用float.TryParse来转换Textbox中之前和之后的值,然后比较两者的转换结果。
在如下代码中,实现了控件textBox1中输入数字。
在控件textBox1中的KeyPress时间中输入如下代码
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 )
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (textBox1.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(textBox1.Text, out oldf);
b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
判断keychar的值。限制只能输入数字,小数点,Backspace,del这几个键。数字0~9所
对应的keychar为48~57,小数点是46,Backspace是8,小数点是46。
2.输入小数点。输入的小数要符合数字的格式,类似9.9.9这样的是不能够输入的。做法就是用float.TryParse来转换Textbox中之前和之后的值,然后比较两者的转换结果。
在如下代码中,实现了控件textBox1中输入数字。
在控件textBox1中的KeyPress时间中输入如下代码
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 )
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (textBox1.Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(textBox1.Text, out oldf);
b2 = float.TryParse(textBox1.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}
2013-12-14
展开全部
在文本框的 KeyPress事件里面判断private void cboId_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(e.KeyChar >= '0' && e.KeyChar <= '9') && (int)e.KeyChar != 8)
{
e.Handled = true;
}
}
{
if (!(e.KeyChar >= '0' && e.KeyChar <= '9') && (int)e.KeyChar != 8)
{
e.Handled = true;
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2013-12-14
展开全部
用得着楼上的这么麻烦吗?try{ Age=int.Parse(txtAge.Text);}catch{ //输入的不是数字.} 事件想写在哪儿就写在哪儿.
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2013-12-14
展开全部
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true;
} com_course_num.DroppedDown = true;
在文本框的KeyPress事件中写,e.KeyChar表示你所按键盘的ACSII,0~9对应着48~57,8表示退格键。
{
e.Handled = true;
} com_course_num.DroppedDown = true;
在文本框的KeyPress事件中写,e.KeyChar表示你所按键盘的ACSII,0~9对应着48~57,8表示退格键。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2013-12-14
展开全部
用正则this.value = this.value.replace(/\D+/,"");
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询