.netwinformsuser-controls

ToolstripControlHost'ed CheckedListBox overflow problem


I have a ToolStripDropDownButton containing a ToolStripControlHost containing a CheckedListBox in C#, like so:

checkedListBox = new CheckedListBox();
dropDownButton = new ToolStripDropDownButton("Button");
host = new ToolStripControlHost(checkedListBox);
dropDownButton.DropDownItems.Add(host);

Everything works fine until the number of items in the CheckedListBox grows the checklistbox outside the screen bounds and the ToolStripDropDown draws the 'tiny triangle button' at the top and bottom to scroll the menu up or down. Whenever I click to scroll, I crash in System.Windows.Forms.ToolStripItemCollection.this[].get with this exception:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

I suspect that since the ToolStripDropDownButton only really has one item (the host) this is the cause of my exception. If that is the case would anybody have any workarounds?


Solution

  • Your guess is correct. The problem is in the .NET logic when to display the scrollbar buttons (in ToolStrip.SetDisplayedItems) which is:

    bool verticallyContained = clientBounds.Contains(clientBounds.X, item.Bounds.Top) && 
                            clientBounds.Contains(clientBounds.X, item.Bounds.Bottom);
    if (!verticallyContained) { 
        allContained = false;
    }
    

    The logic is: "If we have a control off the bottom, allow scrolling". However there is no additional control to scroll to.

    Best answer is: "Don't do this."


    EDIT: To prevent the crash, create and add a second ToolStripControlHost. You will still not be able to access the bottom check items, but at least the app will survive.