繁体   English   中英

从会话中检索多个值以填充ListBox

[英]Retrieveing multiple values from session to populate ListBox

我正在尝试从将值存储为列表的会话变量中检索多个值。 这是我应用的代码,但这只给出了输出列表中的第l个值。 我真的很感谢您的帮助!

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();
        }

谢谢!

首先,您执行多个查询,每个查询返回一行,然后在循环中重新绑定它。 您应该在一个查询中获取所有行,然后将结果绑定到您的控件。

你可能会有更多这样的运气:

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();
    }
}

列表框一次只能绑定一件事。 声明主列表,扫描数组,在循环中运行sql,将结果添加到主列表,然后(在循环外)将ListBox2绑定到主列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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