0

I wanted to know if I can add to the existing SQL Server query in ASP.NET code. I have multiple drop-down menus, check boxes and buttons in the designer. I have a checkbox where if one or more items are selected, it adds to the query.

For example: I have a checkbox called PositionList with multiple positions: Sales, Marketing, Tech Support, HR, and Finance and I wish to create a table where I can select one or more item and get a result of people from those positions.

public partial class _Default : Page
{
    string connection1 = "Server = myserver" 
    string querystring1 = "select name, age, gender, race, city,convert(varchar, datehired, 100) as 'Date Hired', position from NewEmployeesList"
}
...

protected void btnnormal_Click(object sender, EventArgs e)
{
    SqlConnection conn1= new SqlConnection(connection1)
    SqlCommand command1 = new SqlCommand(queryString1, conn1);

    DataTable table1 = new DataTable();

    conn1.Open();
    command1.CommandTimeout = 300; 

    Data1.Fill(table1)

    string DoH = query
    GridView1.DataSource = table1;
    GridView1.DataBind();

    // the table works fine up until this point
    foreach (ListItem li in PositionList.Items)
    {
        if (li.Selected == true)
        { 
            queryString1 + " and position = " + PositionList.SelectedItem;
        }
    }

    // this is the part where I am a stuck, not sure how to add to the 
    // SQL Query properly and how I can check multiple checkboxes so it 
    // returns the table with those positions  

1 Answer 1

1

You can use in query

queryString1 = " and position IN( ";
List<string> selected = new List<string>();
  foreach (ListItem li in PositionList.Items)
{
    if (li.Selected == true)
    { 
     selected.Add( PositionList.SelectedItem);
    }
}
 // values in comma
 queryString1+=string.Join(",", selected.Select(x => $"'{x}'"))

  queryString1+=")";
Sign up to request clarification or add additional context in comments.

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.