为什么if else
条件仅适用于最后一个文本框?我希望我的代码对于每个等于textbox6的文本框都成立。
con.Open();
SqlCommand cmd = new SqlCommand("Select * from compare", con);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
textBox5.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
private void button2_Click_1(object sender, EventArgs e)
{
if (textBox7.Text == textBox1.Text)
{
label1.Text = "this is equal to Box1";
}
if (textBox7.Text == textBox2.Text)
{
label1.Text = "this is equal to textBox1";
}
if (textBox7.Text == textBox3.Text)
{
label1.Text = "this is equal to Box3";
}
if (textBox7.Text == textBox4.Text)
{
label1.Text = "this is equal to Box3";
}
if (textBox7.Text == textBox5.Text)
{
label1.Text = "this is equal to Box4";
}
else
{
label1.Text = "Not equal to any";
}
}
答案 0 :(得分:0)
它确实表明前四次检查的相等性,然而,它们会被后续的真实评估所覆盖。在最后一次检查的情况下,textBox5,如果textBox7.Text不等于textBox5.Text,则任何以前的“this is equal to ...”语句都会被“Not equal to any”覆盖。这就是为什么似乎没有任何匹配。
这是一个应该有效的修复:
private void button2_Click_1(object sender, EventArgs e)
{
if (textBox7.Text == textBox1.Text)
{
label1.Text = "this is equal to Box1";
return;
}
if (textBox7.Text == textBox2.Text)
{
label1.Text = "this is equal to Box2";
return;
}
if (textBox7.Text == textBox3.Text)
{
label1.Text = "this is equal to Box3";
return;
}
if (textBox7.Text == textBox4.Text)
{
label1.Text = "this is equal to Box4";
return;
}
if (textBox7.Text == textBox5.Text)
{
label1.Text = "this is equal to Box5";
return;
}
label1.Text = "Not equal to any";
}
我还在你的信息的措辞中修正了许多印刷错误。
答案 1 :(得分:0)
private void button2_Click_1(object sender, EventArgs e)
{
if (textBox7.Text == textBox1.Text)
label1.Text = "this is equal to Box1";
elseif (textBox7.Text == textBox2.Text)
label1.Text = "this is equal to textBox1";
elseif (textBox7.Text == textBox3.Text)
label1.Text = "this is equal to Box3";
elseif (textBox7.Text == textBox4.Text)
label1.Text = "this is equal to Box3";
elseif (textBox7.Text == textBox5.Text)
label1.Text = "this is equal to Box4";
else
label1.Text = "Not equal to any";
}