Search code examples
c#winformsbindingsource

Bindingsource not setting position when using IndexOf


I have a bindingsource bound to a list of custom objects, and I have the following method:

private void SetMyItem(MyItem item)
{
    //Test 1
    if (item != null)
    {
        bsItems.Position = bsItems.List.IndexOf(item);
    }

    //Test 2 
    foreach (var itm in bsItems)
    {
        if (itm.IsEqual(item))
        {
            bsItems.Position = bsItems.List.IndexOf(itm);
            break;
        }
    }
}

The list contains a few items, and one of these is also the parameter passed to the method.

In the first test above, I'm immediately setting the position by getting the index of the passed parameter. The position is -1.

To make sure that the passed parameter is equal to an item in the list, I added the second test. A matching item is found, but the position is still -1.

Why is the binding source not setting the correct position?

EDIT

IsEqual is an extension method that serializes both objects to a binary stream and compares them.

EDIT 2

IndexOf is working as expected. It is returning the correct index. However, setting the Position to this index is not working.


Solution

  • Seems that the only way to get the position to be set correctly is to do:

    bsItems.ResetBindings(false);
    bsItems.Position = bsItems.IndexOf(myItem);