为什么 If else 条件仅对最后一个文本框为真?

Why is the If else condition is only true for the last textbox?

为什么 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";
    }
}

它实际上确实表明前四次检查的相等性,但是,它们不断被后续的真实评估覆盖。在最后一次检查 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";
}

我还修正了您消息中的大量印刷错误。

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";
}