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
比较另一页中的标签。
答案 0 :(得分:1)
所以你需要执行那个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语句!在循环之前执行一次并存储结果...