C# removing items from listbox

后端 未结 16 2251
礼貌的吻别
礼貌的吻别 2020-12-02 00:12

I have a listbox being populated from a SQLDATA pull, and it pulls down some columns that i dont want like OBJECT_dfj, OBJECT_daskd. The key is all of these being with OBJE

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 00:35

    Your question implies that you're willing to modify other parts of the code, even though you can't modify the SQL Statement itself. Instead of removing them from the ListBox Collection, it might be easier to just exclude them in the first place. This code assumes you're connecting to SQL Server:

    void PopulateListBox(ListBox listToPopulate)
    {
        SqlConnection conn = new SqlConnection("myConnectionString"); 
        SqlCommand cmd = new SqlCommand("spMyStoredProc", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            string item = reader.GetString(0); //or whatever column is displayed in the list
            if (!item.Contains("OBJECT_"))
                listToPopulate.Items.Add(item); 
        }
    }
    

    But if you're absolutely determined to do it this way you should check out this question on modifying an enumerable collection while iterating through it.

提交回复
热议问题