Link to home
Start Free TrialLog in
Avatar of mike_allain
mike_allain

asked on

Easy Question (I Think) regarding accessing object properties

Hi All,

I have a button created existing on a form

I can access the button using the following...

form.button.name = "name"
form.button.text = "text"

and so on.

What I would like to do is give the button a name...lets say btnExample so now the button is called btnExample.  I can access the button by:
form.btnExample.text = text

But what if I wanted to store btnExample in a variable lets say

Dim  buttonName = "btnExample"

and then access the contents of that buttons text property using the name of the button stored in the variable...How would one do that.

For example:  I would like to be able to type form.(variableName).text = "text"

Tried finding example of this, etc but not having any luck.

Thanks
Avatar of ZeonFlash
ZeonFlash

You can try a couple of things.  First, implementing a control array (explained here:  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchcreatingcontrolarraysinvisualbasicnetvisualcnet.asp ).  Or you can do a simple loop through all the controls on your form to find the right one.  Obviously, if you don't have a lot of controls, the second option is the simpler one.  Here's an example:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim btnName As String
        Dim controlButton As Control

        btnName = "btnExample"

        If GetControlFromName(controlButton, btnName) Then controlButton.Text = "text"
    End Sub

    Private Function GetControlFromName(ByRef control As Control, ByVal strControlName As String) As Boolean
        For Each ctrl As Control In Me.Controls
            If UCase(ctrl.Name) = UCase(strControlName) Then
                control = ctrl
                Return True
            End If
        Next
        Return False
    End Function
Avatar of Mike Tomlinson
What version VB.Net?
Avatar of mike_allain

ASKER

Visual studio 2005 ver 8

I am currently using the loop method.  I was hoping that there might be ome way I could use a varaible instead as I have many text boxes on my form.



ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much, this is exactly what I have been looking for. Much better than the looping that I have been doing.