如何制作第三个文本框取决于c#中的第一个和第二个文本框
本文关键字:文本 第一个 第二个 取决于 何制作 三个 | 更新日期: 2023-09-27 18:29:34
我遇到了这个问题或这种情况的问题。我有五个文本框,其中前两个textbox
用户需要键入任何值,然后接下来的两个文本框将通过使用插入的值和一些条件来显示结果。最后,另一个textbox
将根据显示的结果显示新的结果。
这就是我尝试过的:
private void textBox3_TextChanged(object sender, EventArgs e)
{
float value;
if (float.TryParse(textBox3.Text, out value))
{
if (value < 1)
{
textBox4.Text = "1C";
}
else if (value >= 1 && value <2)
{
textBox4.Text = "5T";
}
else if (value >= 2)
{
textBox4.Text = "NG";
}
}
else
{
textBox4.Text = "";
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
float value;
if (float.TryParse(textBox1.Text, out value))
{
if (value < 2)
{
textBox2.Text = "2T";
}
else if (value < 5 || value==2)
{
textBox2.Text = "5T";
}
else if (value > 5 )
{
textBox2.Text = "NG";
}
else
{
textBox2.Text = "NG";
}
}
else
{
textBox2.Text = "";
}
}
如果用户在"textBox3
"中输入值,它将在"textBox4
"中显示结果,如果用户在"textBox1
"中输入值,则会在"textBox2
"中显示结果
我想使用"textBox4
和textBox2
"中的值来进行一些条件检查,然后在"textBox84
"处显示新结果。
我试图创建代码并将其放入加载函数,但什么都没有出现:
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Please choose the correct FORM .",
"Important Message !");
var a = textBox4.Text.ToString();
var b = textBox2.Text.ToString();
if (a == "NG" && b == "NG")
{
textBox84.Text = "s";
}
}
首先,与textBox3_TextChanged
不同,textBox1_TextChanged
中的条件可以简化为这样,
private void textBox1_TextChanged(object sender, EventArgs e)
{
float value;
if (float.TryParse(textBox1.Text, out value))
{
if (value < 2)
{
textBox2.Text = "2T";
}
else if (value < 5) //value==2 can be removed since it is covered in value < 5
{
textBox2.Text = "5T";
}
else //simply put else here, it is equivalent to what you did
{
textBox2.Text = "NG";
}
}
else
{
textBox2.Text = "";
}
}
其次,由于您对textBox84
的检查条件仅在表单加载期间完成,
//This is in the Form1_Load
if (a == "NG" && b == "NG")
{
textBox84.Text = "s";
}
则不太可能随着CCD_ 13和CCD_。所有的初始化实际上都是在Form1()
构造函数中完成的,在InitializeComponent
之后,而不是在Form1_Load
中
为了安全起见,应该像对textBox1
和textBox3
所做的那样,为textBox2
和textBox4
制作事件处理程序
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox84.Text = textBox2.Text == "NG" && textBox4.Text == "NG" ? "s" : "";
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
textBox84.Text = textBox2.Text == "NG" && textBox4.Text == "NG" ? "s" : "";
}
这样,您的textBox84
会真正响应textBox2
和textBox4
TextChanged
事件,而不是Form1_Load
事件。
旁注:
表达式
if (textBox2.Text == "NG" && textBox4.Text == "NG")
textBox84.Text = "s";
else
textBox84.Text = "";
可以进一步简化为
textBox84.Text = textBox2.Text == "NG" && textBox4.Text == "NG" ? "s" : "";
如果使用三元运算符