Click here to Skip to main content
Licence 
First Posted 2 Jun 2004
Views 49,295
Bookmarked 9 times

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

By | 2 Jun 2004 | Article
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

About the Author

Ankhara

Web Developer

Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralBetter still PinmemberMember 39355375:44 9 Apr '08  
GeneralThanks! PinmemberRustyLeeWamu11:53 20 Oct '06  
Generalgetting object dynamically PinsussAnonymous5:58 8 Apr '05  
GeneralI think here will better than Pinmembercucgachthe22:01 17 Nov '04  
GeneralRe: I think here will better than PinmemberNasenbaaer8:37 20 Mar '07  
GeneralUmmm Pinsusssnakeware055518:22 3 Jun '04  

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

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 3 Jun 2004
Article Copyright 2004 by Ankhara
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid