验证仅用于数字输入的文本框字段. [英] Validating a Textbox field for only numeric input.

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

问题描述

我创建了一个基于表单的程序,需要一些输入验证.我需要确保用户只能在距离文本框内输入数值.

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.

到目前为止,我已经检查了 Textbox 中是否有内容,但如果它有一个值,那么它应该继续验证输入的值是否为数字:

So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value is numeric:

else if (txtEvDistance.Text.Length == 0)
        {
            MessageBox.Show("Please enter the distance");
        }
else if (cboAddEvent.Text //is numeric)
        {
            MessageBox.Show("Please enter a valid numeric distance");
        }

推荐答案

你可以试试 TryParse 方法,该方法允许您将字符串解析为整数并返回指示操作成功或失败的布尔结果.

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}

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

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