Close a control by name

Is there a way to reference and close a control (basic, custom or otherwise) by name? For example:
CloseControlByName(“UserNameField”)

Controls names have to be unique in the editor I see most questions saying to create a global array of added things and then iterating through it. Is this the only way?
I tried deleting a custom container control but it doesn’t find the name (using the exact name):

// Remove Control  RemoveCard(cardName as String)
For i As Integer = 0 To cardArray.Count
  Select Case cardArray(i).name
  Case cardName
    cardArray(i).Close
  End Select
Next

Seems like there are special ways to interact with every object type since I added this with:
b.EmbedWithin(window, pos_x, pos_y)
instead of:
MainScreen.AddControl(b)

Which has been confusing when looking at documentation.

Each window has an iterable element called controls. You could do this:

For Each c As DesktopControl In Self.Controls
  If c.name = "SomeName" Then
     c.Close
  End If
Next

If you are using a Container control you would have to deal with the controls that are within it in a separate method. It too has a Controls set. ContainerControls are effectively another ‘window’ embedded within the real window, rather than just a group of controls.

You can access the controls as

Self.ContainerName.ControlName.property

However, that would only work if the scope of the control allows code outside of the container to see it.

Could I close the container as a whole? Or do the controls in the container need to be individually closed? Can I loop through the indexes and handle controls based off of their type like DesktopControl and Containers? Your initial code hit an illegalCastException due to this.

This didn’t work for me:

For i As Integer= 0 In MainScreen.ControlCount
  If(MainScreen.ControlAt(i).Name= cardName)
    MainScreen.ControlAt(i).Close
  End If
Next

Yes, you can close a container:

Self.ContainerName.Close

No need to close the parts within.

You can work with types as follows:

For Each c As DesktopControl In Self.Controls
  If c IsA DesktopTextField Then
    DesktopTextField(c).Enabled = False
  End If
Next

or

For Each c As DesktopControl In Self.Controls
  Select case c
     case IsA DesktopContainer
         // Do something
     case IsA DesktopTextField
         DesktopTextField(c).Enabled = False
     else
         // Do this
  End select
Next
2 Likes

If my container name on the window is “card_x” where x is the card number then what would this look like?
c in your examples has no property ContainerName and just calling close gives me the Illegal cast error. Apologies for all the questions I appreciate your time!

If the code is in the window somewhere it would look like:

card_x.Close

If the code is on the container then

Self.close

If the container is part of a control set then you would have to include the index:

card_x( 1 ).Close