项目列在列表框中,我想使用foreach从SQL中删除项目

时间:2015-01-29 08:14:12

标签: sql listbox sql-delete

private void SearchTable()
        {
            try
            {
                    using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=Steripack;Integrated Security=True"))
                    {
                        foreach (var item in lstCompleted.Items)
                        {
                        string killtag = item.ToString();
                        con.Open();
                        using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = " + killtag))
                        {
                            command.ExecuteNonQuery();
                            lstCompleted.Items.Add("Removed: " + killtag);
                        }
                        con.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "SQL Failed..." + ex;
            } 
        }

2 个答案:

答案 0 :(得分:1)

首先,使用sql-parameters而不是字符串连接。否则你打开sql注入。您还必须为该命令分配连接。

但是,这里还有另一个问题:您正在修改您在foreach中枚举的集合。

一种方法:使用另一个集合来存储稍后要添加的项目:

using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=Steripack;Integrated Security=True"))
{
    List<string> deletedMessages = new List<string>();
    foreach (object item in lstCompleted.Items)
    {
        int killtag = int.Parse(item.ToString());
        con.Open();
        using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = @killtag", con))
        {
            command.Parameters.Add(new SqlParameter("@killtag", SqlDbType.Int).Value = killtag);
            command.ExecuteNonQuery();
            deletedMessages.Add("Removed: " + killtag);
        }
        //con.Close(); // unnecessary with using
    }
    foreach (string deletedMsg in deletedMessages)
        lstCompleted.Items.Add(deletedMsg);
}

另一种方法是将您要删除的项目存储在foreach中列举的另一个集合中:

List<string> toDelete = lstCompleted.Items.Cast<string>().ToList();
foreach (string item in toDelete)
{
    int killtag = int.Parse(item);
    con.Open();
    using (SqlCommand command = new SqlCommand("DELETE FROM tblAsset1 WHERE tagID = @killtag", con))
    {
        command.Parameters.Add(new SqlParameter("@killtag", SqlDbType.Int).Value = killtag);
        command.ExecuteNonQuery();
        lstCompleted.Items.Add("Removed: " + killtag);
    }
}

请注意,第一行中的.ToList()是必不可少的,因为它会创建一个不同的,无关联的列表,而不会引用ObjectCollection中的Listbox.Items

答案 1 :(得分:0)

看起来您还没有为您的连接分配sqlcommand对象

SqlCommand(&#34; DELETE FROM tblAsset1 WHERE tagID =&#34; + killtag,Con)