1

i have the code of passing a selected value in the the query and that value will bind the data in the girdview. the selection is made with the Listbox.. I want to pass a list param of S_ID

Now I want to modify my program a little i want to pass a list of param. in the query.. so that this can enable multiple selection list in the listbox.. I've searched over Internet and i couldnt find a certain satisfying answer... I'm not very good at query.

 protected void Button2_Click(object sender, EventArgs e)
{
    OleDbConnection con = new OleDbConnection();
    con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database11.accdb";
    con.Open();
    for (int i = 0; i < ListBox1.Items.Count; i++)
    //foreach(Items Item in Listbox1)
  {
        if (ListBox1.Items[i].Selected == true)
        {
            string Skill_ID = ListBox1.Items[i].Value;
            string query1 = "SELECT *FROM Emp AS E, Junction AS J WHERE E.E_ID=J.E_ID And J.S_ID=@Skill_ID";
            OleDbCommand cmd1 = new OleDbCommand(query1, con);
            cmd1.Parameters.AddWithValue("@Skill_ID", Skill_ID);

            OleDbDataReader rs = cmd1.ExecuteReader();
            if (rs.HasRows)
            {
                GridView1.DataSource = rs;
                GridView1.DataBind();
                rs.Close();
            }
4

1 回答 1

2
//use LINQ to obtain the selected id values as strings
var selectedItems = ListBox1.Items.Cast<ListItem>().Where(p => p.Selected == true).Select(p => p.Value).ToList();

//now concat them as a comma seperated string
var idCommaList = string.Join(', ', selectedItems);

//Now use a WHERE IN () statement instead with your query and concat your comma seperated list of ids into the sql statement
var query1 = @"SELECT * 
              FROM Emp AS E, Junction AS J 
              WHERE E.E_ID = J.E_ID AND J.S_ID IN (" + idCommaList + ")";
于 2013-11-09T08:25:33.140 回答