winformsc#-4.0objectlistview

How to ensure that the newly added node in treelistview is selected and visible?


I am using BrightIdeasSoftware TreeListView control. When I add a new node in the list, I want the new item to be visible and selected. I want the list to be automatically scrolled down to ensure its visibility.

I have written the following function to achieve this

public void EnsureNodeIsVisible(object item)
{
    // Select the new node
    treeListView.SelectedObject = item;

    // Refresh the object in the TreeListView
    treeListView.RefreshObject(item);

    // Ensure the model is visible (this should scroll to it)
    treeListView.EnsureModelVisible(item);

    // Expand the new node
    treeListView.Expand(item);

    // Force the TreeListView to scroll to the selected item
    var olvItem = treeListView.ModelToItem(item);
    if (olvItem != null)
    {
        treeListView.FocusedItem = olvItem;
        olvItem.EnsureVisible();
    }

    // Alternatively, if the node is at the end, manually scroll to the bottom
    int maxIndex = treeListView.Items.Count - 1;
    if (treeListView.SelectedIndex == maxIndex)
    {
        treeListView.EnsureVisible(maxIndex);
    }

    // Scroll the ListView to the item index to force visibility
    treeListView.ScrollToIndex(olvItem.Index);
}

internal static class TreeListViewExtensions
{
    public static void ScrollToIndex(this TreeListView treeListView, int index)
    {
        if (index >= 0 && index < treeListView.Items.Count)
        {
            treeListView.Items[index].EnsureVisible();
        }
    }
}

But the list wouldn't scroll down to ensure the new node is visible and selected. What am I missing here?


Solution

  • You may be overthinking it?

    This seems to work fine for me

    var person = new Person("Person");
    treeListView.AddObject(person);
    treeListView.SelectedObject = person;
    treeListView.Expand(person);
    treeListView.EnsureModelVisible(person);
    

    It properly scrolls down and even seems to consider, that all sub-items of the expanded node are visible.