Skip to content
Advertisement

C# Multiple comboBoxes used in MySQL Where

Im trying to learn using MySQl with C# so im creating app that allow sorting and adding data to my tables.

That is code that i use to show items selected only by my comboBox_1 value. But now i want to add 2nd comboBox and show data that meets both conditions. The problem is i have no idea how to get there. I thought using multiple ifs that check if combobox have any items selected but my code is looking monstrous then.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(comboBox1.SelectedIndex >= 0)
            {
                MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM narzedzia.narzedzia where status='" + comboBox1.Text + "'", Program.connection);
                if (Program.connection.State == ConnectionState.Closed) { Program.connection.Open(); }
                

                DataSet ds = new DataSet();
                adapter.Fill(ds, "narzedzia");
                dataGridView1.DataSource = ds.Tables["narzedzia"];
                Program.connection.Close();
            }
            
        }```

Advertisement

Answer

I usually start with a basic select statement ( I use where 1 = 1 so I can just start adding and statements when my conditions are met)

so maybe something like this

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM narzedzia.narzedzia where 1 = 1 ");
    
    if(comboBox1.SelectedIndex >= 0){
        adapter.SelectCommand = adapter.SelectCommand + " and status = @status ";
        adapter.SelectCommand.Parameters.AddWithValue("@status", comboBox1.Text );
    }
    
    if(comboBox2.SelectedIndex >= 0){
        adapter.SelectCommand = adapter.SelectCommand + " and color = @color ";
        adapter.SelectCommand.Parameters.AddWithValue("@color", comboBox2.Text );
    }
      
    DataSet ds = new DataSet();
    adapter.Fill(ds, "narzedzia");
    dataGridView1.DataSource = ds.Tables["narzedzia"];     
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement