检查是否选择了组合框值 - C#.net

时间:2013-05-06 17:08:13

标签: c# .net if-statement combobox messagebox

我试图通过处理异常来提高我的应用程序。我有一个表单,如果所有字段都没有完成,则向用户显示一个消息框。以下是我的尝试,但即使所有领域都已完成,它仍然不会让我通过。

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();
}

4 个答案:

答案 0 :(得分:3)

你可以尝试一下:

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();
 }

答案 1 :(得分:1)

TextBox的Text值设置为空字符串“”,而不是null。接下来,我将使用ComboBox.SelectedIndex而不是使用ComboBox.SelectedValue,并检查它不是-1(如果没有选择任何内容,则为默认值)。

 if (textBox1.Text == "" || comboBox3.SelectedIndex == -1 
     || comboBox4.SelectedIndex == -1 || comboBox5.SelectedIndex == -1 
     || comboBox8.SelectedIndex == -1)

答案 2 :(得分:0)

不检查它是否为空。 检查文本长度是否大于0

答案 3 :(得分:0)

你也可以尝试这个....

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))