Search code examples
c#objectlistview

Save and restore selection in ObjectListView


Can anybody tell my how to keep selection in ObjectListView?

I have a list of objects in my control which I receive from a database. User selects one and then hits "Refresh" (so that all items are retrieved from the database again). Selection is "jumping", but I want it to keep on a user selected object.

I must compare objects by their unique id, so that sorting or new objects from the database must not impact on user selection.

Thanks in advance.


Solution

  • Issue:

    Once you clear objects and build the list again selected items disappear regardless of you are keeping it in a variable or not. Because to keep this info the variable for selected items must be declared as a variable which is dynamically attached to OLV control. That's why once the list is cleared the variable won't be able to keep selected items.

    About workaround:

    I have a workaround for this issue. Most of people may think to implement objectListViewUserList.SelectedItem property but this property has some issues. It is not consistent with some reason. So for my workaround, I will introduce this property objectListViewUserList.MouseMoveHitTest. It sounds like it's a test variable but it works like a charm.

    Assumption:

    Additionally, to implement this workaround, it is assumed that first column is the ID column.

    Workaround:

    Here's the workaround. Keep the text information of the first column in a public string in the click event.

        private void objectListViewUserList_Click(object sender, EventArgs e)
        {
            if (objectListViewUserList.MouseMoveHitTest.Item != null)
                selectedItemText = objectListViewUserList.MouseMoveHitTest.Item.Text;
            else
                selectedItemText = "";
        }
    

    In my application, I refresh the OLV control with fillOnlineUsers method. This is arbitrary. It can be any method. In my application this method works with a timer. After each refresh, I select the items by searching the ID in the new list.

        public void fillOnlineUsers()
        {
            objectListViewUserList.ClearObjects();
            objectListViewUserList.AddObjects(onlineUsers);
            objectListViewUserList.BuildList();
            if (selectedItemText != "")
            {
                foreach (OLVListItem olvi in objectListViewUserList.Items)
                    if (olvi.Text == selectedItemText)
                        olvi.Selected = true;
            }
        }
    

    This workaround has O(n) complexity. Which means it may slow down your application if you have thousands of records.