如何验证仅包含数字的文本框 [英] how to validate textbox that contains only numeric

查看:55
本文介绍了如何验证仅包含数字的文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证我的文本框只包含数字值C#windows form application

解决方案

尝试这样

< pre lang =cs> public Form1()
{
InitializeComponent();
txtHomePhone.KeyPress + = new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress( object sender,KeyPressEventArgs e)
{
if (e.KeyChar > ; = ' 0'&& e.KeyChar < = ' 9' || e.KeyChar == < span class =code-string>' ' // 该字符代表退格
{
e.Handled = false ; // 请勿拒绝输入
}
else
{
e.Handled = true ; // 拒绝输入
}
}





参考:

验证 - 是否为文本框仅包含数字 [ ^ ]

验证文本框到允许仅数字值 [ ^ ]


Please尝试如下。



  private   void  textBox1_KeyPress( object  sender,KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&&!char.IsDigit(e.KeyChar)
&& e.KeyChar!= ' 。'
{
e.Handled = true ;
}

// 只允许一个小数点
if (e.KeyChar == ' 。'
&&(sender as TextBox).Text.IndexOf('' 。'> -1)
{
e.Handled = true ;
}
}







欲了解更多信息: 如何制作仅接受数字的文本框


您可以用两种方式编写代码:



1.在文本框的中KeyPress 事件,点击KeyChar,如果它不在数字范围内,则将KeyChar设置为0.



2.在文本框的验证事件,检查内容 int.TryParse double.TryParse 视具体情况而定并提醒用户。



执行上述两项操作将确保您的文本框仅包含数字。


i want to validate my textbox that only contains numerics values nothing else in C# windows form application

解决方案

Try like this

public Form1()
{
    InitializeComponent();
    txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true; //Reject the input
    }
}



Refer:
validating-whether-a-textbox-contains-only-numbers[^]
validating-a-textbox-to-allow-only-numeric-values[^]


Please try is as below.

private void textBox1_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;
    }
}




For more info : How do I make a textbox that only accepts numbers


You can write code in two ways:

1. In the Textbox's KeyPress event, tap the KeyChar and if it is not not within the range for numebers, set the KeyChar to 0.

2. In the Textbox's Validate event, Check the contents with int.TryParse or double.TryParse as the case may be and alert the user.

Doing both of the above will ensure that your textbox contains only numbers.


这篇关于如何验证仅包含数字的文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆