[英]Textbox maximum/minimum numeric values C#
I want to create an if
Statement that validates whether an input number in a textbox is between 0 to 100. For example: 我想创建一个
if
语句来验证文本框中的输入数字是否介于0到100之间。例如:
NumericUpDown num = new NumericUpDown();
num.Maximum = 100;
num.Minimum = 0;
if (int.Parse(txtMid.Text) < num.Minimum && int.Parse(txtMid.Text) > num.Maximum)
{
MessageBox.Show("Please input 0 to 100 only.");
}
That's all. 就这样。 Thanks in advance.
提前致谢。
You need to parse the txtbox1.Text string into an integer: 您需要将txtbox1.Text字符串解析为整数:
int val = 0;
bool res = Int32.TryParse(txtbox1.Text, out val);
if(res == true && val > -1 && val < 101)
{
// add record
}
else
{
MessageBox.Show("Please input 0 to 100 only.");
return;
}
Also, do you need to test one or two textboxes? 另外,您需要测试一个或两个文本框吗? If it's only one and you need the interval 0, 100, then your condition is wrong, because it always returns false (a number cannot be at the same time <= -1 and >= 101).
如果它只是一个并且你需要间隔0,100,那么你的条件是错误的,因为它总是返回false(一个数字不能同时<= -1和> = 101)。
VERY IMPORTANT : I have reversed your if/else: you have to print the error in the else and add the record in the if. 非常重要 :我已经颠倒了你的if / else:你必须在else中打印错误并在if中添加记录。
First convert the text into Int then you can compare it. 首先将文本转换为Int然后您可以比较它。 But be careful the entered text might not be the number for example user can enter abc instead of 12
但要小心输入的文本可能不是数字,例如用户可以输入abc而不是12
You can use Int.TryParse(String)
method to check whether the textbox contains valid number or not. 您可以使用
Int.TryParse(String)
方法检查文本框是否包含有效数字。 If the number is valid then apply the if condition below 如果该数字有效,则应用下面的if条件
if(Convert.ToInt32(txtbox1.Text) <= -1 && Convert.ToIn32(textbox2.Text >= 101)
{
}
其他答案回答了您的直接问题,但输入数字的更好选择是使用NumericUpDown
控件将输入限制为数字,并提供旋转控件。
Essentially what you want to do is the following: 基本上你想要做的是以下内容:
TryParse
method for the type). TryParse
方法)。 TextBox.Text property will return value as a string. TextBox.Text属性将返回值作为字符串。 So, first you have to parse the that string into integer.
所以,首先你必须将该字符串解析为整数。 You can use following code :
您可以使用以下代码:
int num = -2;
bool conversionSuccessful = int.tryParse(txtbox1.Text, out num);
if(conversionSuccessful) {
if (num <= -1 && num >= 101) {
MessageBox.Show("Please input 0 to 100 only.");
return;
}
}
You can find more information about conversion here and here 您可以在此处和此处找到有关转换的更多信息
int val1=0,val2=0
try
{
val1 = Convert.ToInt32(txtbox1.Text);
val2 = Convert.ToIn32(textbox2.Text);
}
catch
{
MessageBox.Show("Invalid Input");
}
// Do all the Checking here....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.