Click here to Skip to main content
15,894,362 members
Articles / Programming Languages / Visual Basic
Article

Get a reference to a winform control from its' string name

Rate me:
Please Sign up or sign in to vote.
1.33/5 (11 votes)
2 Jun 2004 79.9K   10   6
A small function to get a reference to a control from it's name.

Introduction

Have you ever tried to get a reference to a winform control that you have added to a container? I was bl...y annoyed to find out that Microsoft hadn't included that obvious functionality in VB.NET, so I wrote a function to do it. It requires the control container and the name of the control you are looking for.

Code

 Function getControlFromName(ByRef containerObj As Object, _
                          ByVal name As String) As Control
    Try
       Dim tempCtrl As Control
       For Each tempCtrl In containerObj.Controls
          If tempCtrl.Name.ToUpper.Trim = name.ToUpper.Trim Then
             Return tempCtrl
          End If
       Next tempCtrl
    Catch ex As Exception
    End Try
 End Function

Use

To use it, enclose it in a CType function to give you a useful reference to the control. Like this..

 Dim tempCtrl As Button = _
 CType(getControlFromName(TabControl1.TabPages(tabIndex), "btnName"), Button)


That's it! Hope you find it useful. :D

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralBetter still Pin
Rajeev ARSD9-Apr-08 5:44
Rajeev ARSD9-Apr-08 5:44 
GeneralThanks! Pin
RustyLeeWamu20-Oct-06 11:53
RustyLeeWamu20-Oct-06 11:53 
Generalgetting object dynamically Pin
Anonymous8-Apr-05 5:58
Anonymous8-Apr-05 5:58 
GeneralI think here will better than Pin
cucgachthe17-Nov-04 22:01
cucgachthe17-Nov-04 22:01 
GeneralRe: I think here will better than Pin
Nasenbaaer20-Mar-07 8:37
Nasenbaaer20-Mar-07 8:37 
Hey good. You are great! Thats what the world is looking for. Send this code to Microsoft. Because it is more than needed. I used the Me.Controls.Add methode to add some Pictureboxes. But If I ask the Funktion FindControl, it does return "NOTHING". But the name is very 100% the right one.

any idea?

GeneralUmmm Pin
snakeware05553-Jun-04 18:22
susssnakeware05553-Jun-04 18:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.