C# 将sql语句的结果存储到字符串中,并将其与列表框中选定的项进行比较
我想将上述SQL语句中的详细信息存储到一个字符串中,并与C# 将sql语句的结果存储到字符串中,并将其与列表框中选定的项进行比较,c#,asp.net,sql-server-2008,C#,Asp.net,Sql Server 2008,我想将上述SQL语句中的详细信息存储到一个字符串中,并与 在列表框中选择的项目。比较后,如果它们相等,我希望响应。将比较的标签重定向到另一页中。因此您需要执行该SQL并返回结果: foreach (ListItem li in ListBox1.Items) { SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Securi
在列表框中选择的项目。比较后,如果它们相等,我希望
响应。将比较的标签重定向到另一页中。因此您需要执行该SQL并返回结果:
foreach (ListItem li in ListBox1.Items)
{
SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
const string SQL = "SELECT EventName FROM Event)";//the result of this statement to be stored in a string
if (li.Selected = //the string)//compare here
{
Response.Redirect("asd.aspx?name=" + a);//at here i want to use the compared value
}
}
const string SQL=“从事件中选择事件名”//此语句的结果将存储在字符串中
List eventNames=新列表();
//设置SQL连接和命令
使用(SqlConnection con=newsqlconnection(@“Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true”))
使用(SqlCommand cmd=newsqlcommand(SQL,con))
{
con.Open();
//获取SqlDataReader以读取多行
使用(SqlDataReader rdr=cmd.ExecuteReader())
{
//虽然有更多的结果行。。。。。
while(rdr.Read())
{
//从结果行中获取0索引值
Add(rdr.GetString(0));
}
}
con.Close();
}
foreach(ListBox1.Items中的ListItem li)
{
//对于列表框中的每个选定项目-检查其.Text
//包含在从数据库表检索的事件名称列表中
if(li.Selected&&eventNames.Contains(li.Text))
{
Response.Redirect(“asd.aspx?name=“+resultFromSQL”);
}
}
此外,由于您执行的连接和SQL似乎都不依赖于循环中的任何内容,因此不要不必要地反复执行此SQL语句!在循环之前执行一次并存储结果…如果事件表中有多个EventName,会发生什么?@Tim:很好-我添加了一个TOP 1
来获取第一个。从这个问题上看,我肯定不清楚在这种情况下会发生什么……我同意。OP(IMO)有一个潜在的设计缺陷,他需要解决。顺便说一句,我的评论不是对你答案的批评,从OP提供的信息来看,这是正确的:)@marc_s非常感谢你帮助我。我尝试了这些代码,它们工作得非常好。非常感谢您的帮助。@tim感谢您提醒我如果存在多个eventname的话。这真的很有帮助。再次感谢
const string SQL = "SELECT EventName FROM Event"; //the result of this statement to be stored in a string
List<string> eventNames = new List<string>();
// set up SQL connection and command
using(SqlConnection con = new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true"))
using(SqlCommand cmd = new SqlCommand(SQL, con))
{
con.Open();
// get a SqlDataReader to read multiple rows
using(SqlDataReader rdr = cmd.ExecuteReader())
{
// while there are more result rows.....
while(rdr.Read())
{
// grab the 0-index value from the result row
eventNames.Add(rdr.GetString(0));
}
}
con.Close();
}
foreach (ListItem li in ListBox1.Items)
{
// for each of the selected items in the ListBox - check if their .Text
// is contained in the list of event names retrieved from the database table
if (li.Selected && eventNames.Contains(li.Text))
{
Response.Redirect("asd.aspx?name=" + resultFromSQL);
}
}