我正在尝试从会话变量中检索多个值,其中我将值存储为List。这是我应用的代码,但这只给出了输出列表中的第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();
}
谢谢!
答案 0 :(得分:2)
首先,您执行多个查询,每个查询返回一行,然后在循环中重新绑定它。您应该在一个查询中获取所有行,然后将结果绑定到您的控件。
你可能会有更多这样的运气:
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();
}
}
答案 1 :(得分:0)
列表框一次只能绑定一件事。声明主列表,扫描数组,在循环中运行sql,将结果添加到主列表,然后(在循环外)将ListBox2绑定到主列表。