我正在编写一个函数,以从列表框中获取尽可能多的多个选定项目,并将值传递给 SQL 查询,以便在从另一个表中选择过滤后的值后将值插入表中。我输入的代码如下,它似乎不起作用(问题在于我将字符串传递给查询的方式。
string lbSites = "";
protected void Button1_Click1(object sender, EventArgs e)
{
string cns = "server=abc;database=testDB;Trusted_Connection=True";
using (SqlConnection con = new SqlConnection(cns))
{
using (SqlCommand command = con.CreateCommand())
{
command.CommandText = "INSERT INTO Activity (Hostname,Site,Status,System_Dept,Business_Dept)"
+ "SELECT * FROM Inventory WHERE Site IN ("+lbSites+");"
;
con.Open();
command.Parameters.AddWithValue("@lbSites", lbSites);
command.ExecuteNonQuery();
con.Close();
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.Items.Count > 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
lbSites += "'" + ListBox1.Items[i].Value + "', ";
}
}
}
}