Find controls on a windows form

Hi,

I have a windows form with several controls on it. I need a function which finds a specific control on this form. Is there any function for that already built  If not, could you advice me how to tackle this problem

Thanking you in advance,
Mily


Answer this question

Find controls on a windows form

  • RubenBrenes

    Controls added into the form are added to the Controls collection property of the form.  You can iterate through this collection to find your specific control.  

    Problem is this iteration is through integral indexing (0 to Controls.Count - 1).  If you are looking for a specific control given its name, you have to check the name for each control that you are iterating.  Controls stored on the Controls collection are of Control type, the IS and AS operators will be helpful on your iteration.

    Don't forget that containers such as Panel can have controls in them, so you need to search through their Controls collection property also if you need to...

  • PavanS

    I know that this is an old post but there is an easier way to find a control on a windows form.

    If you are adding your controls at runtime, add them to a hashtable when you create them and then anytime you need to find a control, code the following:

    'Global declaration
    Private m_Controls as New Hashtable

    'Add to hashtable when you create them
    Dim lbl as New Label
    lbl.Name = "lblMyLabel"
    m_Controls.Add(lbl)

    'and then in your event or function
    Dim lbl As Control
    lbl = DirectCast(m_Controls.Item("lblMyLabel"), Label)

    This way you don't have to loop through all the controls.

    Hope this helps,
    Greg

  • Per Nilsson

    Well...

    You can use Form.Controls loop though them, and compare the name and/or type.

    Cant remmember if there is a function called FindControl in Windows.Forms, but maybe try that too.

  • Find controls on a windows form