Reputation: 29
I am trying to make my application better by handling exceptions. I have a form where if all the fields are not completed then show a message box to the user. Following is what I have attempted but even if all the fields are completed it still wont let me pass.
if (textBox1.Text == null || comboBox3.SelectedValue == null ||
comboBox4.SelectedValue == null ||
comboBox5.SelectedValue == null || comboBox8.SelectedValue == null)
{
MessageBox.Show("Please make sure you don't have any missing fields");
}
else
{
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
// Insert into table_name values ("","name","1")
command.CommandText = @"insert into CustomTests values ('','" + textBox1.Text + "'," + Convert.ToBoolean(checkBox1.CheckState) + ",'" + comboBox3.Text + "'," + comboBox4.Text + "," + comboBox5.Text + ",'" + comboBox8.Text + "'," + comboBox2.Text + "," + Timer_Enabled + ",'" + comboBox1.Text + "')";
command.ExecuteNonQuery();
}
Upvotes: 1
Views: 10612
Reputation: 45
You can try this Out also....
if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(this.comboBox3.Text) || string.IsNullOrEmpty(this.comboBox4.Text) ||
string.IsNullOrEmpty(this.comboBoxSelect5.Text)|| string.IsNullOrEmpty(this.comboBox8.Text))
Upvotes: 0
Reputation: 7351
You can try this out:
if (string.IsNullOrEmpty(textBox1.Text) || comboBox3.SelectedIndex == -1 || comboBox4.SelectedIndex == -1 ||
comboBox5.SelectedIndex == -1 || comboBox8.SelectedIndex == -1)
{
MessageBox.Show("Please make sure you don't have any missing fields");
}
else
{
connection.Open();
//update the settings to the database table
MySqlCommand command = connection.CreateCommand();
// Insert into table_name values ("","name","1")
command.CommandText = @"insert into CustomTests values ('','" + textBox1.Text + "'," + Convert.ToBoolean(checkBox1.CheckState) + ",'" + comboBox3.Text + "'," + comboBox4.Text + "," + comboBox5.Text + ",'" + comboBox8.Text + "'," + comboBox2.Text + "," + Timer_Enabled + ",'" + comboBox1.Text + "')";
command.ExecuteNonQuery();
}
Upvotes: 3
Reputation: 5938
A TextBox's Text
value is set to an empty string, "", rather than null
. Next, instead of using ComboBox.SelectedValue, I would use ComboBox.SelectedIndex and check that it was not -1 (the default value if nothing is selected).
if (textBox1.Text == "" || comboBox3.SelectedIndex == -1
|| comboBox4.SelectedIndex == -1 || comboBox5.SelectedIndex == -1
|| comboBox8.SelectedIndex == -1)
Upvotes: 1
Reputation: 505
Don't check whether it is null or not. Check whether the length of text is greater than 0
Upvotes: 0