Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: Create variable whose name is stored in a variable - VB.NET  (Read 15679 times)

0 Members and 2 Guests are viewing this topic.

camerongray

    Topic Starter


    Expert
  • Thanked: 306
    • Yes
    • Cameron Gray - The Random Rambings of a Computer Geek
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Mac OS
Create variable whose name is stored in a variable - VB.NET
« on: March 03, 2011, 12:02:29 PM »
Hi,

I'm working on a program where I need to declare a variable but the name for this variable is stored in another variable (strange I know) but I have no idea how to do this.  I'm using VB.NET 2010.  I'm sorry if that's not very clear, I'm not very good at describing things :P.

Thanks in advance

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: Create variable whose name is stored in a variable - VB.NET
« Reply #1 on: March 03, 2011, 02:16:29 PM »
I don't believe that is possible; sounds more like what you are trying to do could be facilitated using other means (my first thought would be a Dictionary- then you could use the string "name" to lookup the appropriate value. I believe in VB.NET A Generic Dictionary is created using:

Code: [Select]
Dim DictVar As Dictionary(Of String,Object)
where Object can of course be whatever type you intend to be using.

If you can provide more details on what exactly you are trying to do with the program, I'm sure me or somebody else could suggest something that could work for you.
I was trying to dereference Null Pointers before it was cool.

camerongray

    Topic Starter


    Expert
  • Thanked: 306
    • Yes
    • Cameron Gray - The Random Rambings of a Computer Geek
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Mac OS
Re: Create variable whose name is stored in a variable - VB.NET
« Reply #2 on: March 03, 2011, 02:42:25 PM »
The part of the program that this is for occurs when the user selects a menu item they are prompted by means of an input box to enter a name for a button control, the button is then added to the form with that specific name.

This is the code i'm using to create the button - "CONTROL_NAME" is where I'd want the name from the variable to be added.
Code: [Select]
Dim CONTROL_NAME As New Button

CONTROL_NAME.Text = TempButtonName
CONTROL_NAME.Size = New Size(100, 50)
CONTROL_NAME.Location = New Point(100, 100)
Me.Controls.Add(CONTROL_NAME)

All I want is to be able to add a control such as a button to the form that has a name specified by the user.

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: Create variable whose name is stored in a variable - VB.NET
« Reply #3 on: March 03, 2011, 03:31:47 PM »
Ahh, I see what you are trying to do.

Well, it looks more like you would want to use an array- or, more precisely (and as I noted earlier) a dictionary. After all, it would be utterly pointless to have the variable name not known until run-time, because the code that is supposed to use and manipulate that variable are written far earlier.

Here is one approach to dynamically adding Buttons; I use a dictionary.

-Create a Form (just stick with Form1) in a new test app; Create a textbox and a button (use the default names), ideally laid out near the top, with some vertical space underneath.
-Paste the following into the Declarations Section:

Code: [Select]
Dim CurrentYPos As Integer
Dim LoadedButtons As Dictionary(Of String, Button) = New Dictionary(Of String, Button)()

The "CurrentYPos" variable is used for purely aesthetic purposes; LoadedButtons is used to keep track of all the buttons loaded so far. Note that it is "indexed" using the name the user specified.

In the Button1 Click event, paste this:

Code: [Select]
  'get the name to use from the string.

        Dim newbuttonname As String = TextBox1.Text
        If newbuttonname = "" Then
            MessageBox.Show("You must specify a Name.")

        ElseIf LoadedButtons.Contains(newbuttonname) Then
            MessageBox.Show("Name Already Exists.")
        Else

            'Create the button
            Dim createdButton = New Button()
            createdButton.Name = newbuttonname
            createdButton.Text = "Button named " + newbuttonname
            createdButton.Location = New Point(TextBox1.Left, CurrentYPos)
            createdButton.Size = Button1.Size
            createdButton.Width = TextWidth(createdButton.Text, createdButton.Font) * 2
            CurrentYPos += createdButton.Height
            'use "CreatedClick" for it's event handler
            AddHandler createdButton.Click, AddressOf CreatedClick
            Controls.Add(createdButton)
            LoadedButtons.Add(newbuttonname, createdButton)
        End If



Code: [Select]
Control

the Load event of the Form requires this, otherwise it starts the buttons at the top of the form:

[code]
CurrentYPos = TextBox1.Bottom + 5

And lastly, paste this at the bottom of the code listing:

Code: [Select]
Private Function TextWidth(ByVal measurestring As String, ByVal useFont As Font) As Integer
        Dim usebitmap As Bitmap = New Bitmap(1, 1)
        Dim Useg As Graphics = Graphics.FromImage(usebitmap)
        Return Useg.MeasureString(measurestring, useFont).Width

    End Function
    Private Sub CreatedClick(ByVal Sender As Object, ByVal Args As EventArgs)
        Dim gotcontrol As Control = Sender
        MessageBox.Show("You clicked on " + gotcontrol.Name)
    End Sub

One notable portion is the use of "AddHandler" to link <ALL> of the buttons to the same Event procedure. I feel that this may in many ways be the sort of thing you need (I'm guessing you want to handle the events of controls you add but the only way you were aware of was the use of the Handles clause on the end of a Sub definition, but that needs a control name, thus the requirement to have "user-defined" control names, etc).

After that, it's added to the Controls collection of the form, and then to the LoadedButtons Dictionary. The latter is purely for Access purposes- without it, it would be difficult to reference the controls outside their event procedures (the AddClick routine) since they wouldn't really have any Form-level reference. (note that controls that you add to a form aren't made implicitly available by the form as "properties" like those you add at design time; the Form Designer creates boilerplate code that adds properties for the controls you add at design time, but no such addition is done at run-time, so you have to do that management yourself.

Using this method, you can also access a specific control using the "name": that the user gave it, via the dictionary:

Code: [Select]
String choosebuttonname="Whatever"
If LoadedButtons.ContainsKey(choosebuttonname) Then
    Button chosenbutton = LoadedButtons[choosebuttonname].Value
Else
    MessageBox.Show("Control name not found.")
End If


I hope this helps.

 

I was trying to dereference Null Pointers before it was cool.

camerongray

    Topic Starter


    Expert
  • Thanked: 306
    • Yes
    • Cameron Gray - The Random Rambings of a Computer Geek
  • Certifications: List
  • Computer: Specs
  • Experience: Expert
  • OS: Mac OS
Re: Create variable whose name is stored in a variable - VB.NET
« Reply #4 on: March 03, 2011, 03:52:32 PM »
That's great - Thanks!  ;D