0

I am filtering a data grid view with a TextBox in a ToolStripControlHost that is in the items of a ToolStripDropDown.

I can see the exact number of times I use the TextBox in the Visual Studio Memory Usage snapshot while debugging and they never disappear.

I have already attempted to catch all the disposing events and dispose their children as shown below but they remain in memory.

private void TxtFilter_Disposed(object sender, EventArgs e)
{
    CueTextBox filter = sender as CueTextBox;
    filter.KeyPress -= CmdFilter_Submit;

    for (int ix = filter.Controls.Count - 1; ix >= 0; --ix)
    {
        // If Dispose is not called then the controls will leak forever.
        filter.Controls[ix].Dispose();
    }
}

How do I dispose of these correctly?

    private void DisplayFilter(DataGridViewCellMouseEventArgs e)
    {
        int minWidth = MINIMUM_FILTER_WIDTH > Columns[e.ColumnIndex].Width ? MINIMUM_FILTER_WIDTH : Columns[e.ColumnIndex].Width;

        CueTextBox TxtFilter = new CueTextBox
        {
            Cue = "Filter",
            Size = new Size(minWidth, 30),
            Tag = Columns[e.ColumnIndex].Name
        };
        
        var popup = new ToolStripDropDown
        {
            AutoSize = false,
            Margin = Padding.Empty,
            Padding = Padding.Empty
        };
        //popup.Closed += Popup_Closed;

        ToolStripControlHost host = new ToolStripControlHost(TxtFilter)
        {
            Margin = Padding.Empty,
            Padding = Padding.Empty,
            AutoSize = false,
            Size = TxtFilter.Size
        };
        //host.Disposed += Host_Disposed;

        popup.Size = TxtFilter.Size;
        popup.Items.Add(host);
        popup.Show(this, GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).X, GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Bottom);
        TxtFilter.Focus();
    }
NinjaLlama
  • 167
  • 3
  • 14
  • See the notes about the custom ToolStripControlHost here: [How to add Controls, as a toolbar, to a ContextMenuStrip?](https://stackoverflow.com/a/65280439/7444103) -- You shouldn't need to create a whole bunch on new Controls each time a Cell is clicked. Build something more permanent and configurable, as shown there -- BTW, it's not clear what a `CueTextBox` is, why you're trying to dispose child Controls of this thing and also unsubscribe from an event you have never subscribed to in your sample code – Jimi Jul 03 '23 at 00:28
  • Sorry, I have been removing extra stuff to get to when the issues start. The event and button child control were removed to see if they were the cause. – NinjaLlama Jul 03 '23 at 00:34

0 Answers0