简体   繁体   English

从数据库中删除列表框中的现有项目

[英]Remove existing items in listbox from database

I am trying to delete the items within the listbox, which already exists in my database.我正在尝试删除列表框中的项目,该项目已存在于我的数据库中。 My listbox is populated by a set of random names, and the ones that are equal to the data from the table rows should be deleted.我的列表框由一组随机名称填充,应删除与表行中的数据相等的名称。 My code:我的代码:

        SqlCommand RemoveUserName = new SqlCommand("SELECT * FROM Name WHERE ([Name] = @check)", Con);
        RemoveUserName.Parameters.AddWithValue("@check", listbox1.Items);
        SqlDataReader dr = RemoveUserName.ExecuteReader();
        if (dr.HasRows)
        {
            listBox1.Items.Remove(); // ?? Remove the names which are already in the database

        }
        else
        {
          // remain in listbox
        }

Getting an error in my parameter value and I don't know how to delete the said items.在我的参数值中出现错误,我不知道如何删除所述项目。

EDITED my current code:编辑我当前的代码:

    SqlCommand RemoveUserName = new SqlCommand("SELECT * FROM Name", Con);
    SqlDataReader dr = RemoveUserName.ExecuteReader();
        while (!dr.Read())
        {
            for (int i = 0; i < listBox1.Items.Count; ++i)
            {
                if (listBox1.Items[i].ToString() == dr["Name"].ToString())
                    listBox1.Items.Remove(listBox1.Items[i]);
            }
        }

Has no error anymore, but is still not functional.不再有错误,但仍然无法正常工作。

WORKING CODE:工作代码:

          for (int i = listBox1.Items.Count - 1; i >= 0; --i)
        {
            using (var cmd = new SqlCommand("UPDATE [Name] SET [Name] = Name WHERE [Name] = @name", Con))
            {
                cmd.Parameters.AddWithValue("@name", listBox1.Items[i].ToString());
                if (cmd.ExecuteNonQuery() > 0)
                {
                    listBox1.Items.RemoveAt(i);
                }
          }
        }

Thanks @ LarsTech谢谢@LarsTech

It helps to loop backwards through the list in order to avoid indexing issues:它有助于在列表中向后循环以避免索引问题:

for (int i = listBox1.Items.Count - 1; i >= 0; --i) {
  using (var cmd = new SqlCommand("DELETE FROM [Name] WHERE [Name] = @name", Con)) {
    cmd.Parameters.AddWithValue("@name", listBox1.Items[i].ToString());
    if (cmd.ExecuteNonQuery() > 0) {
      listBox1.Items.RemoveAt(i);
    }
  }
}

ExecuteNonQuery will return the number of records affected, so if it's greater than zero, the name was found and deleted. ExecuteNonQuery 将返回受影响的记录数,因此如果它大于零,则该名称已被找到并被删除。

Make sure to close your connection object, too.确保也关闭您的连接对象。 Best by putting it also in a using block the way the SqlCommand object is in my example.最好将它也放在 using 块中,就像我的示例中的 SqlCommand 对象一样。

Your table and column names need to be improved.您的表名和列名需要改进。

As I understood,据我了解,

1) You need to delete items from listbox that already exists in your database and read by SqlDataReader. 1) 您需要从数据库中已存在的列表框中删除项目并由 SqlDataReader 读取。

You first need to loop into reader.您首先需要循环到阅读器中。 So instead of !所以,而不是! while(reader.Read()) use while(reader.Read()) while(reader.Read())使用while(reader.Read())

2) Now you want to remove actual item from listbox, if it exists in reader. 2)现在您想从列表框中删除实际项目,如果它存在于阅读器中。

So try to do following to remove item from listbox inside reader while loop因此,请尝试执行以下操作以while循环时从reader内的listbox删除项目

for (int n = listBox.Items.Count - 1; n >= 0; --n)
  {
    var removelistitem = dr["Name"].ToString();
    if (listBox.Items[n].ToString().Contains(removelistitem))
      {
        listBox.Items.RemoveAt(n);
      }
  }

Now after while loop execution.现在在while循环执行之后。 your listbox will only have items not present in your reader (data from database).您的列表框将只包含阅读器中不存在的项目(来自数据库的数据)。

Hope this helps.希望这可以帮助。

Edit编辑

Its ok to loop in listbox items.可以在列表框项目中循环。

Use RemoveAt instead.请改用 RemoveAt。 (See above answer) (见上面的回答)

try this:尝试这个:

    while (!dr.Read())
    {
        for (int i=0; i<listBox1.Items.Count; ++i)
        {
            if (listBox1.Items[i].ToString() == dr["columnName"].ToString())
                listBox1.Items.Remove(listBox1.Items[i]);
        }
    }

SqlReader must be read before use it. SqlReader必须在使用前阅读。 If there's no rows in the Reader, code in while block won't be executed.如果 Reader 中没有行,则不会执行while块中的代码。

EDIT I got a problem making you unhappy....编辑我有一个问题让你不开心....

The code you provided:您提供的代码:

RemoveUserName.Parameters.AddWithValue("@check", listbox1.Items);

Is wrong, because @check parameter expects string , but you provided was ObjectCollection .是错误的,因为@check参数需要string ,但您提供的是ObjectCollection Revise query "SELECT * FROM Name WHERE ([Name] = @check)" to "SELECT * FROM Name" .将查询"SELECT * FROM Name WHERE ([Name] = @check)""SELECT * FROM Name" and remove the line AddWithValue .并删除行AddWithValue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM