1

I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

4 Answers 4

3

It is important to parameterize as well:

private const string _select = "select * from country";

void DoSomething()
{
     string sql = string.Empty;
     if (combobox1.SelectedIndex > -1)
     {
         command.Parameters.AddWithValue("@1",  (string)combobox1.SelectedValue);
         sql = " where city_name = @1";
     }
     sql = _select + sql;
     command.CommandText = sql;
     command.Execute...
}

@un-lucky asked me how would I deal with many conditions - here is one way

var conditions = new List<string>();     
if (/* condition 1*/)
{
    command.Parameters.AddWithValue("@2",  (string)cboN.SelectedItem);
    conditions.Add("col1 = @2");
}
if (/* condition 2*/)
{
    command.Parameters.AddWithValue("@3",  textBoxN.Text);
    conditions.Add("col2 = @3");
}

if (conditions.Count > 0)
    sql = _select + " where " + string.Join(" AND ", conditions.ToArray());
Sign up to request clarification or add additional context in comments.

4 Comments

What happens if you have few more conditions?
@un-lucky Then it is different question. There are many ways to solve it. One - build each condition to field = @parameter and add to list. Check if list contains any items, then add WHERE and join your list items using " AND " as delimiter. This is one solution
@un-lucky actually, a bit different technique though.
Looks fine now..!
0

You can use the shorthand if only if you have two conditions:

 string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);

Hope it helps!

1 Comment

" where city_name = " + combobox1.text <-- incorrect
0

I think you have to try something like this with parameterization:

StringBuilder queryBuilder = new StringBuilder("Select * from country Where 1=1 ");
SqlCommand cmdSql = new SqlCommand();

if (combobox1.selectedindex > -1) 
{
   queryBuilder.Append(" And city_name = @city_name "); 
   cmdSql.Parameters.Add("@city_name", SqlDbType.VarChar).Value = combobox.text;  
}
else if(Condition 2)
{
   queryBuilder.Append(" And column2 = @col2 "); 
   cmdSql.Parameters.Add("@col2", SqlDbType.VarChar).Value = "some Value here;  
}
// Build the query like this
cmdSql.CommandText= = queryBuilder.ToString();
cmdSql.Connection = conObject;
// Here you can execute the command

Comments

-1

I have a sample, try it

string select = this.combobox1.GetItemText(this.combobox1.SelectedItem); cm1 = new SqlCommand("Select * from country where city_name=@select or @select is null", con);
            cm1.Parameters.Add("@select", SqlDbType.NVarChar, 50);
            cm1.Parameters["@select"].Value = select;
            dap = new SqlDataAdapter(cm1);
            ds = new System.Data.DataSet();
            dap.Fill(ds, "DATABASE");
            //DataGridView1.DataSource = ds.Tables[0]; get data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.