检查文本框输入一个十进制数或不 - C# [英] Check if TextBox input is a decimal number or not - C#
问题描述
我的目标:我想文本框接受像123.45或0.45或1004.72十进制数。如果像a或b或c字母的用户类型,程序应该显示一条消息,提醒用户仅输入号码
My Goal: I want textbox to accept the decimal numbers like 123.45 or 0.45 or 1004.72. If the user types in letters like a or b or c, the program should display a message alerting the user to input only numbers.
我的问题:我的代码只检查是否像1003或567或1。不检查小数像123.45或0.45号码。我如何为十进制数字我的文本框检查?下面是我的代码:
My Problem: My code only checks for numbers like 1003 or 567 or 1. It does not check for decimal numbers like 123.45 or 0.45. How do I make my text box check for decimal numbers? Following is my code:
namespace Error_Testing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string tString = textBox1.Text;
if (tString.Trim() == "") return;
for (int i = 0; i < tString.Length; i++)
{
if (!char.IsNumber(tString[i]))
{
MessageBox.Show("Please enter a valid number");
return;
}
}
//If it get's here it's a valid number
}
}
}
我对您的帮助提前一个新手,谢谢。 :)
I am a newbie and Thanks for your help in advance. :)
推荐答案
使用的 Decimal.TryParse
来检查,如果输入的字符串是小数与否。
use Decimal.TryParse
to check if the string entered is decimal or not.
decimal d;
if(decimal.TryParse(textBox1.Text, out d))
{
//valid
}
else
{
//invalid
MessageBox.Show("Please enter a valid number");
return;
}
这篇关于检查文本框输入一个十进制数或不 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!