[英]Text Box to accept all values in Windows Form C#
I have wrote a program for arithmetic operations. 我已经写了一个用于算术运算的程序。 Results are working fine.
结果运行良好。 But I would like to go ahead a bit.
但我想继续前进。 I want a text box, that accepts all values like Positive, Negative Values, Decimal Values (Int, Float, Long, Double) excpet String or Character.
我想要一个文本框,它接受所有值,例如正值,负值,十进制值(整数,浮点数,长整数,双精度),例如字符串或字符。 While String or Character is entered, it should throw an error message (i will do it in Message box with try & Catch)
输入String或Character时,它应该引发错误消息(我将在try和Catch的消息框中执行此操作)
private void button1_Click(object sender, EventArgs e)
{
int num1, num2, res;
num1 = int.Parse(textBox1.Text);
num2 = int.Parse(textBox2.Text);
res = num1 * num2;
textBox3.Text = (num1 * num2).ToString();
}
Use TryParse
, change num1
and num2
types for the most general one ( double
): 使用
TryParse
,将num1
和num2
类型更改为最通用的一种( double
):
private void button1_Click(object sender, EventArgs e) {
// double as the most general numeric type
double num1, num2;
if (!double.TryParse(textBox1.Text, out num1)) {
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show(String.Format("\"{0}\" is not a valid value", textBox1.Text));
}
else if (!double.TryParse(textBox2.Text, out num2)) {
if (textBox2.CanFocus)
textBox2.Focus();
MessageBox.Show(String.Format("\"{0}\" is not a valid value", textBox2.Text));
}
else
textBox3.Text = (num1 * num2).ToString();
}
You can use try catch, and use your variable as float so that you can free to input float and int data in textbox input 您可以使用try catch,并将变量用作float,以便可以在文本框输入中自由输入float和int数据
private void button1_Click(object sender, EventArgs e)
{
float num1, num2, res;
try
{
num1 = float.Parse(textBox1.Text);
}
catch (Exception)
{
MessageBox.Show("Error");
}
try
{
num2 = float.Parse(textBox2.Text);
}
catch (Exception)
{
MessageBox.Show("Error");
}
res = num1 * num2;
textBox3.Text = (num1 * num2).ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.