CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Nov 2010
    Posts
    42

    Search listbox for string and return index

    I want to search a listbox control that has a list of usernames. I am developing an irc client and when the user leaves it calls and event with that user. This event needs to search the listbox full of users, return the index of the item in the listbox then remove it.

    I have tried:

    ListBox lst = _List(split[2].ToString()); //This just grabs the listbox that is on the tab of the correct
    //channel.

    foreach (object o in lst.Items)
    {
    if (o.ToString() == user)
    {
    lst.Items.Remove(o);
    }
    }

    That does not work though. Any help is appreciated and thanks in advance.

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Search listbox for string and return index

    Have you used the debugger to see what values you are actually comparing?

  3. #3
    Join Date
    Nov 2010
    Posts
    42

    Re: Search listbox for string and return index

    Yes, it is succesfully cycling through the listbox and the comparing o.ToString() does infact hold the text of the item, but I get a runtime error at lst.Items.Remove(o);

    InvalidOperationException
    List that this enumerator is bound to has been modified. An enumerator cannot be used if this list doesn not change.

  4. #4
    Join Date
    Nov 2010
    Posts
    42

    Re: Search listbox for string and return index

    I must have been too tired last night the solution was way to easy. Obviously the problem was removing an item from the list inside the foreach loop, so I made a work around:

    Code:
    object op = null;
                            foreach (object o in lst.Items)
                            {
                                if (o.ToString() == froms || o.ToString() == "@" + froms)
                                {
                                    op = o;
                                    break;
                                }
                            }
                            if (op != null)
                                lst.Items.Remove(op);

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured