gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:03 24 4
gpt4 key购买 nike

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 并取回结果:

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 语句!在循环之前做一次并存储结果...

关于c# - 将 sql 语句的结果存储到字符串中,并将其与列表框中选择的项目进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com