1

In PHP and a few other languages, I know that there is a way for a program to dynamically call the name of a control using Visual Basic.NET?

For example: if you have a control named txtQuestionValue15.text on a WinForm, is there a way to set up some kind of loop to go back and get through 1 through 14 and disable them, or do I have to manually edit in.

I was thinking of using something like this SELECT Case statement to try:

    Select Case trkNoOfQuestions.Value
        Case 1
        Case 2
        Case 3
        Case 4
        Case 5
        Case 6
        Case 7
        Case 8
        Case 9
        Case 10
        Case 11
        Case 12
        Case 13
        Case 14
        Case 15
            ' Enable Question 15
            txtQuestionTL15.Enabled = True
            txtQuestionTL15.Text = 45
            txtQuestionValue15.Enabled = True
            txtQuestionValue15.Text = 1000000

    End Select
3
  • 1
    there are several ways to do something like that - store the names in a List and loop thru that - the list could contain a class which contains the TL and Value controls. Commented Aug 6, 2015 at 0:03
  • Use DataGridView control Commented Aug 6, 2015 at 13:10
  • Care to give an example of how to use a DataGridView in this instance? Commented Aug 6, 2015 at 13:17

1 Answer 1

2

You can use a loop and a string to find the control. You must check the control collection where they reside - here I am using the form.

For i As Integer = 1 To 15
 Dim tb As Textbox = TryCast(Me.Controls("txtQuestionTL" & i.ToString), Textbox)
 If Not tb Is Nothing Then 
 'now you have the textbox based on the name
 End If
Next

Alternatively you do a search no matter what container they live in:

For i As Integer = 1 To 15
 Dim tbs = Me.Controls.Find("txtQuestionTL" & i.ToString, True)
 If tbs.Count > 0 Then
   Dim tb As TextBox = tbs.First 
 End If
Next
Sign up to request clarification or add additional context in comments.

2 Comments

So would I have to use the name txtQuestionTL1 for the control or is there a way to express the loop as a two digit number?
Since i = 1 and not 01 just rename them to match the counter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.