C# 验证文本框是否只包含数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15399323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating whether a textbox contains only numbers
提问by Jayseer
So I have an idea, because i find it hard to make a code for txtbox that will only allow integer and not a letters in mysql using c#. My Plan is why not set the database column into integer instead of typical varchar and if ever you put a letter of course it will turn and exception so in that case I want to catch the exception and prompt a messagebox saying "Please enter only integer". What do you think?
所以我有一个想法,因为我发现很难为 txtbox 编写一个代码,它只允许使用 c# 的 mysql 中的整数而不是字母。我的计划是为什么不将数据库列设置为整数而不是典型的 varchar 并且如果你放一个字母当然会变成异常所以在这种情况下我想捕获异常并提示一个消息框说“请只输入整数” . 你怎么认为?
采纳答案by Simon M?Kenzie
It's a good idea to use the correct column datatype for what you plan to store in it, but it's very easy to check whether a string contains only numbers - just parse and see if an error is returned:
为您计划在其中存储的内容使用正确的列数据类型是个好主意,但检查字符串是否仅包含数字很容易 - 只需解析并查看是否返回错误:
int parsedValue;
if (!int.TryParse(textBox.Text, out parsedValue))
{
MessageBox.Show("This is a number only field");
return;
}
// Save parsedValue into the database
回答by Tapan kumar
You can achieve it this way
你可以通过这种方式实现它
int outParse;
// Check if the point entered is numeric or not
if (Int32.TryParse(propertyPriceTextBox.Text, out outParse) && outParse)
{
// Do what you want to do if numeric
}
else
{
// Do what you want to do if not numeric
}
回答by Prince Sharma
Visual studio has built in support for this (and you may also achieve it via coding). Here's what you need to do:
Visual Studio 内置了对此的支持(您也可以通过编码实现)。您需要执行以下操作:
- Switch to design view from markup view.
- Now click on design view and press Ctrl+Alt+X.
- From the toolbox that opens click on Validation and drag a compare validator near your
TextBox
. - Right click on the compare validator and choose properties, now locate
ErrorMessage
and write "Alert: Type only Number". - In Control to Validate choose your control.
- In the Operator choose DataTypeCheck and in the Type choose Integer.
- 从标记视图切换到设计视图。
- 现在单击设计视图并按Ctrl+ Alt+ X。
- 从打开的工具箱中单击验证并将比较验证器拖动到您的
TextBox
. - 右键单击比较验证器并选择属性,现在找到
ErrorMessage
并写入“警报:仅输入数字”。 - 在 Control to Validate 中选择您的控件。
- 在 Operator 中选择 DataTypeCheck,在 Type 中选择 Integer。
Also via coding you can get it as:
同样通过编码,你可以得到它:
protected void Button1_Click(object sender, EventArgs e)
{
int i;
if (!int.TryParse(textBox.Text, out i))
{
Label.Text = "This is a number only field";
return;
}
}
回答by Tarckhan Badirov
if(Int32.TryParse(textBox1.Text, out int value))
{
// Here comes the code if numeric
}
else
{
// Here comes the code if not numeric
}