Search code examples
c#sqlselectwhere-clause

I am trying to search a database with values from combo boxes


I am familiar with SQL syntax and am trying to create a windows form in C#. My goal is to achieve something like this:

Select * 
From comboBox1 
Where Name = comboBox2 And Station = comboBox3

Here is my code:

private void searchBtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(@"Data Source=WIN-0P8I7F78SRV\SQLEXPRESS02;Initial      Catalog=bakFile;Integrated Security=True");

    SqlCommand cmd = new SqlCommand(String.Concat("Select * From ", watershedCombo.Text), con);
    cmd.CommandType = CommandType.Text;

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    dt.TableName = "Bluemountains";

    dataGridView1.DataSource = dt;
}

Running form

It retrieves the info from the database on the combo box but I am not sure how to further filter it using the values from the other comboboxes.

Just to clarify, in the running form, Watershed = comboBox1

Any input would be greatly appreciated.

Thank you.


Solution

  • From what I understand is that you have one table per watershed and each watershed table has (at least) a Name and a Station. My inner software architect gets triggered by such a design but I will keep him quiet.

    So what I would do is to use a parametrized query. The basic idea is that you define a SQL-query with placeholders for values that you will feed in dynamically.

    I have no way of actually testing this but something along these lines should do the trick:

    using (var connection = new SqlConnection(@"Data Source=WIN-0P8I7F78SRV\SQLEXPRESS02;Initial      Catalog=bakFile;Integrated Security=True"))
    {
        connection.Open();
        
        var cmd = new SqlCommand($"SELECT * FROM {watershedCombo.Text} WHERE Name = @Name AND Station = @Station", connection);
        cmd.Parameters.AddWithValue("@Name", nameCombo.Text);
        cmd.Parameters.AddWithValue("@Station", stationCombo.Text);
        
        var da = new SqlDataAdapter(cmd);
        var dt = new DataTable();
        da.Fill(dt);
        dt.TableName = "Bluemountains";
    
        dataGridView1.DataSource = dt;
    }
    

    The @-prefixed strings are considered parameters. Those are replaced with actual values through cmd.Parameters.AddWithValue("@ParamName", <ParamValue>)

    You can read more about parameters in the C# docs here or here

    Update: I forgot that you can not use a table name as a parameter. Sorry. Updated my answer.