Jose M.
Jose M.

Reputation: 2340

Remove all buttons from panel except for one

I have the following procedure on my button that adds a button on a panel for every item on my database. What I want to add to the procedure is to remove from the panel all previous existing controls except for the one named btnAddItemName. I have no idea how to accomplish that. I can add controls, remove and clear all of them, but not how to make an exception. Here is what I have so far:

Private Sub btnCategory_Click(sender As Object, e As EventArgs) Handles btnCategory.Click

    Dim source As DataTable = ItemInventoryControlTableAdapter.GetData

    For Each row As DataRow In source.Rows

        Dim btn As New InventoryItemButton()

        btn.Name = DirectCast(row("ItemName"), String)
        btn.Text = btn.Name

        'Assign the click event to each button
        AddHandler btn.Click, AddressOf handleItemButton

        'Add button to the item panel
        flpItem.Controls.Add(btn)

    Next
    End Sub

Upvotes: 1

Views: 1405

Answers (2)

Deja Vu
Deja Vu

Reputation: 413

Try:

flpItem.Controls.OfType(Of Button).Except({btnAddItemName}).ToList().ForEach(Sub(btn As Button) btn.Dispose())

This will get a List of type Button including all the buttons in the panel (flpItem) except the button which is needed (btnAddItemName), then iterates through the List and Dispose each Button.

To simplify:

flpItem.Controls.OfType(Of Button).Except({btnAddItemName}).ToList().ForEach(AddressOf RemoveButton)
Sub RemoveButton(btn As Button)
    btn.Dispose()
End Sub

Or:

Dim btnList As List(Of Button) = flpItem.Controls.OfType(Of Button).ToList()
btnList.Remove(btnAddItemName)
For Each btn As Button In btnList
    btn.Dispose()
Next

Upvotes: 1

LarsTech
LarsTech

Reputation: 81645

Try isolating your buttons into a list and then iterate through the list backwards to avoid messing up the index positions:

Dim buttons() As Button = flpItem.Controls.OfType(Of Button)().ToArray
For i As Integer = buttons.Length - 1 To 0 Step -1
  If buttons(i).Name <> btnAddItemName.Name Then
    buttons(i).Dispose()
  End If
Next

Note: Calling flpItem.Controls.Clear does not dispose of those controls.

Upvotes: 0

Related Questions