This code is for a button that removes a column of panels from a program that includes rows and columns of panels, each with a textbox and label inside them.The two buttons and definitions panel "pnlDefintions" adjust the way specified after the For loop, and the program does run through the For loop the correct number of times, but for some reason doesn't seem to remove the panel. Thank you in advance for any help :)

Private Sub btnDelCol_Click(sender As Object, e As EventArgs) Handles btnDelCol.Click
        ' Creates unicode character code for column naming scheme (Alphabetic)
        Dim columnsCode As String = "&H" & (columns + 40).ToString()
        ' For loop removes as many panels as there are rows
        For i As Integer = 1 To rows Step +1
            ' Creates unicode character code for row naming scheme (Numeric)
            Dim rowsCode As String = "&H" & (i + 30).ToString()
            ' Removes panel
            Dim pnl As New Panel
            pnl.Name = "pnl" & ChrW(columnsCode) & ChrW(rowsCode)
            Me.Controls.Remove(pnl)
        Next i
        ' Adjusts column count
        columns -= 1
        ' Moves definitions panel to accomodate one less column
        Dim newPnlX As Integer = (pnlDefinitions.Left - 206)
        Dim newPnlXSize As Integer = (pnlDefinitions.Width + 206)
        pnlDefinitions.Location = New Point(newPnlX, 39)
        pnlDefinitions.Size = New Point(newPnlXSize, 678)
        ' Moves buttons to accomodate one less column
        Dim newBtnX As Integer = (btnAddCol.Left - 206)
        btnAddCol.Location = New Point(newBtnX, 39)
        btnDelCol.Location = New Point(newBtnX, 68)
    End Sub

Recommended Answers

All 5 Replies

Your loop is creating a new Panel (pnl) then trying to remove it from the Me.Controls collection but you never added it to the Me.Controls collection to begin with. If you are trying to get a reference to a panel for deletion then you should not use the New keyword. If pnl.Name is the name of the panel you want to delete then you don't even need to create a reference. You can delete it by

For i As Integer = 1 To rows
    Dim rowsCode As String = "&H" & (i + 30).ToString()
    Dim name As String = "pnl" & ChrW(columnsCode) & ChrW(rowsCode)
    Me.Controls.Remove(name)
Next

Actually, that doesn't work. It gives me a format exception that a string cannot be converted to a panel.

OK. Try

Dim name As String = "pnl" & ChrW(columnsCode) & ChrW(rowsCode)
Dim pnl As Panel = Me.Controls(name)
Me.Controls.Remove(pnl)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.