C# removing items from listbox

后端 未结 16 2200
礼貌的吻别
礼貌的吻别 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:40

    You want to iterate backwards through using a counter instead of foreach. If you iterate forwards you have to adjust the counter as you delete items.

    for(int i=listBox1.Items.Count - 1; i > -1; i--) {
    {
        if(listBox1.Items[i].Contains("OBJECT"))
        {
            listBox1.Items.RemoveAt(i);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 00:40

    You can try this also, if you don't want to deal with the enumerator:

    object ItemToDelete = null;
    foreach (object lsbItem in listbox1.Items)
    {
       if (lsbItem.ToString() == "-ITEM-")
       {
          ItemToDelete = lsbItem;                                  
       }
    }
    
    if (ItemToDelete != null)
        listbox1.Items.Remove(ItemToDelete);
    
    0 讨论(0)
  • 2020-12-02 00:42

    I found out the hard way that if your listbox items are assigned via a data source

    List<String> workTables = hhsdbutils.GetWorkTableNames();
    listBoxWork.DataSource = workTables;
    

    ...you have to unbind that before doing the removal:

    listBoxWork.DataSource = null;
    for (int i = listBoxWork.Items.Count - 1; i >= 0; --i)
    {
        if (listBoxWork.Items[i].ToString().Contains(listboxVal))
        {
            listBoxWork.Items.RemoveAt(i);
        }
    }
    

    Without the "listBoxWork.DataSource = null;" line, I was getting, "Value does not fall within the expected range"

    0 讨论(0)
  • 2020-12-02 00:43

    The problem here is that you're changing your enumerator as you remove items from the list. This isn't valid with a 'foreach' loop. But just about any other type of loop will be OK.

    So you could try something like this:

    for(int i=0; i < listBox1.Items.Count; )
    {
        string removelistitem = "OBJECT";
        if(listBox1.Items[i].Contains(removelistitem))
             listBox1.Items.Remove(item);
        else
            ++i;
    }
    
    0 讨论(0)
提交回复
热议问题