简体   繁体   中英

Retrieveing multiple values from session to populate ListBox

I am trying to retrieve multiple values from the session variable in which I stored the values as List. Here's the code I applied but this gives me only the lst value from the list in the output. I would really appreciate some help!

Array k= yourlist.ToArray();
        for (Int32 i = 0; i < k.Length; i++)
        {
            Int32 x = Convert.ToInt32(k.GetValue(i));
            SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id =" + x, con);
            SqlDataReader dr2 = cmd2.ExecuteReader();
            if (dr2.HasRows)
            {
                while (dr.Read())
                {
                    ListBox2.DataSource = dr2;
                    ListBox2.DataBind();
                }
            }

            dr2.Close();
            cmd2.Dispose();
        }

Thanks!

First of all you execute multiple queries, each returning one line, and you re-bind this in your loop. You should get all the rows in one query, and then bind the results to your control.

You might have more luck with something like this:

List<string> ids = yourlist.Select(o => o.ToString()).ToList();
string idList = string.Join(",", ids);
SqlCommand cmd2 = new SqlCommand("select id,name from plugins where id in ("+idList+")", con);
using( SqlDataReader dr2 = cmd2.ExecuteReader() )
{
    if( dr2.HasRows)
    {
        ListBox2.DataSource = dr2;
        ListBox2.DataBind();
    }
}

The listbox can only be bound to 1 thing at a time. Declare a master list, Scan your array, run your sql in the loop as you do, add the results to a masterlist, then (outside the loop) bind the ListBox2 to the masterlist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM