执行if和else条件

本文关键字:条件 else if 执行 | 更新日期: 2023-09-27 17:59:38

我正在处理windows窗体。我面临着一个非常奇怪的问题。

在其中一个按钮事件处理程序中,我应用了if和else条件。

问题是如果条件和else条件都被执行。

有人能指出我错在哪里吗?

private void button1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true && checkEbayName(textBox1.Text) == true )
            {
                DataSet ds = GetUserByEbayName(textBox1.Text);
                if (ds == null)
                    {
                        return;
                    }
                dataGridView1.DataSource = ds.Tables["Customer"];
            }
            if (radioButton2.Checked == true && checkName(textBox1.Text) == true)
            {
                DataSet ds = GetUserByName(textBox1.Text);
                //if (checkCustomer(textBox1.Text, textBox2.Text) == true)
                //{
                if (ds == null)
                {
                    return;
                }
                dataGridView1.DataSource = ds.Tables["Customer"];
            }
            else
            {
                MessageBox.Show("No Customer with matching details");
            }
        }

执行if和else条件

如果不执行第一个if,则您的else将被解雇。我怀疑您想将else if用于第二个if

根据您的代码,第一个if可能评估为true。然后,该逻辑将落入第二CCD_ 5。如果不满足该条件,则执行else

也许您在first-if中缺少了一个return语句?

if (radioButton1.Checked == true && checkEbayName(textBox1.Text) == true )
{
    DataSet ds = GetUserByEbayName(textBox1.Text);
   if (ds == null)
   {
        return;
   }
   dataGridView1.DataSource = ds.Tables["Customer"];
   return;
}

如果满足匹配if的条件,则永远不会执行else。然而,你必须分开if和第二个并不取决于第一个。你的代码的简化版本是

if(a){
   if(d) {
      return;
   }
}
if(b){}
else{
}

在a或d为false的情况下,执行将进入第二个if。如果b也为false,则执行else。

如果你打算只在a和b都为假的情况下执行else,那么你必须执行以下

if (radioButton1.Checked == true && checkEbayName(textBox1.Text) == true ) {
 //...
} else if (radioButton2.Checked == true && checkName(textBox1.Text) == true) {
  //...
} else {
            MessageBox.Show("No Customer with matching details");
}

如果选中radiobutton1,则执行第一个条件;如果ds is not null,则代码不返回,而是检查第二个If。如果这两个单选按钮互斥,则不可能为true,而执行else。

如果你想在没有客户的情况下显示一个消息框,你可以重写你的代码,在结束时检查空ds

DataSet ds = null;
if (radioButton1.Checked == true && checkEbayName(textBox1.Text) == true )
{
    ds = GetUserByEbayName(textBox1.Text);
    if (ds != null)
        dataGridView1.DataSource = ds.Tables["Customer"];
}
else if (radioButton2.Checked == true && checkName(textBox1.Text) == true)
{
    ds = GetUserByName(textBox1.Text);
    if (ds != null)
        dataGridView1.DataSource = ds.Tables["Customer"];
}
// Show the user that we have not found customers not by ebayname or username
if(ds == null)
    MessageBox.Show("No Customer with matching details");