将 sql 语句的结果存储到字符串中,并将其与列表框中选择的项进行比较

本文关键字:列表 选择 比较 结果 语句 sql 存储 字符串 | 更新日期: 2023-09-27 18:06:48

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
   }
}

我想将上述SQL语句中的详细信息存储到一个字符串中,并将其与在列表框中选择的项。经过比较,如果它们相等,我想在另一页中response.redirect比较的标签。

将 sql 语句的结果存储到字符串中,并将其与列表框中选择的项进行比较

所以你需要执行那个SQL并得到结果:

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

此外,由于连接和您执行的 SQL 似乎都不依赖于循环中的任何内容 - 不要不必要地一遍又一遍地执行此 SQL 语句!在循环之前做一次并存储结果...