Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to be able to use a string to find a variable with the same name, and then use the variable it finds in my code. For example, I'm currently using the below, which uses the known variable column1.
VB
Public Class Form1
    Dim column1 As New DataGridViewTextBoxColumn
    Public Sub New()
        InitializeComponent()
        With column1
            .Name = "column1"
            .HeaderText = "My First Column"
            .SortMode = DataGridViewColumnSortMode.NotSortable
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            .Width = 200
        End With
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        dgv.Columns.Add(column1) '/// column1 as known variable
    End Sub
End Class

Whereas, I want to be able to use something like the below, but I haven't figure out a way to use my string to get the variable. (getvariable doesn't exist, was just an example)
VB
Public Class Form1
    Dim mystring As String = "column1"
    Dim column1 As New DataGridViewTextBoxColumn
    Public Sub New()
        InitializeComponent()
        With column1
            .Name = "column1"
            .HeaderText = "My First Column"
            .SortMode = DataGridViewColumnSortMode.NotSortable
            .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            .Width = 200
        End With
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        dgv.Columns.Add(getvariable(mystring)) '/// See here for what I'm trying to do
    End Sub
End Class
Posted

1 solution

If you really, really want to do that - and it's not clear why on earth you would - the easiest way is to establish a Dictionary which holds the name of your control as the string key, and the object it refers to as the value:
VB
Dim variables As New Dictionary(Of String, Object)()
variables.Add(column1.Name, column1)
...
Dim found As Object = variables("column1")
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900