noeway noeway - 3 months ago 13
C# Question

My if else statement in C# is not working

I'm really having trouble adding a condition that show message when user left the text box blank.I've tried every way that i know of to change it but it's not working at all.I have "5" textbox and hiding and showing them based on selected combobox item value for example if i selected firearm it should all five textbox and if i selected ammo then it should only show three textbox(1,2 and 3).And it should show message box warning me if i left a single textbox blank.

But the problem is during the ammo setting the message box kept showing up even though i have filled all of the textfield.Is there something wrong with my if else statement?

private void insertbtn_Click(object sender, EventArgs e)
{
string mysql = "";
if (comboBox1.SelectedItem.ToString() == "Firearm")
{
mysql = "insert into Firearm(Fid,Fname,Ftype,Manufacturer,Price) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
}
if (comboBox1.SelectedItem.ToString() == "Ammo")
{
mysql = "insert into Ammo(Aid,Atype,Coating,Metal) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
}

if (comboBox1.SelectedItem.ToString() == "Ammo" && textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" )
{
MessageBox.Show("Please Fill all of the text fields");
}
else if (comboBox1.SelectedItem.ToString()=="Firearm" && textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text=="" )
{
MessageBox.Show("Please Fill all of the text fields");
}
else
{
try
{
SqlConnection conn = new SqlConnection(dbsource);
conn.Open();
SqlCommand cmd = new SqlCommand(mysql, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("New Data Inserted!");
conn.Close();
}
catch (SqlException)
{
MessageBox.Show("Error!!!");
}
}
}

Answer

Your problem is probably at this line:

if(comboBox1.SelectedItem.ToString() == "Ammo" && 
   textBox1.Text == "" || 
   textBox2.Text == "" || 
   textBox3.Text == "")

I assume you want to say that is the value is "Ammo" and one of the text boxes are empty: (add another set of ()

if(comboBox1.SelectedItem.ToString() == "Ammo" && 
   (textBox1.Text == "" || 
   textBox2.Text == "" || 
   textBox3.Text == ""))

And same for else if of "Firearm"

Comments