创建文本框的方法仅适用数字 [英] a methods that create textboxs apply only digit
本文介绍了创建文本框的方法仅适用数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,所有亲
我想要一种仅将数字文本框创建调用方文本框的方法
那是什么?????????
请帮帮我吗?
像:
我在表单加载中遇到了这个问题,它只将textbox4用作数字
textbox4.applyonlydigits();
hello all pro
i want a methods that create caller textbox a only numeric textbox
what is that?????????
help me please??
like :
i have this in my form load and it takes textbox4 a only numeric one
textbox4.applyonlydigits();
推荐答案
请尝试以下代码
Hi Try this below code
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//You may make it 4 or 5 depends on your application
if (textBox1.Text.IndexOf(' ') == textBox1.Text.Length - 2)
e.Handled = true;
}
这是纯数字文本框的代码
This is the code for a numeric only textbox
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
但是最好通过添加一个类并继承文本框来创建自定义控件
并覆盖其OnKeyPress事件
But better create a custom control by adding a class and inherit textbox
and override its OnKeyPress Event
using System.Windows.Forms;
namespace Test
{
public partial class NumericTextBox : TextBox
{
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (this as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
}
}
您将在工具箱上获得一个新控件
you will get a new control on your toolbox
这篇关于创建文本框的方法仅适用数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文