0

I am trying to change different values in a for loop in vb.net. However, I couldn't find how to change the numbered boolean variables.

Dim txt1 As Boolean = False
Dim txt2 As Boolean = False
 i = i + 1
            If i < 9 Then
                'I tried to do:
                Me.Controls("txt" & i.ToString) = True
                txt(i) = True
            End If

How can I change the numbered boolean variables and what is the most efficient way to it?

  • 3
    If you enable [`Option Strict On`](https://stackoverflow.com/a/29985039/1115360) for the current project then Visual Studio will guide you to where corrections are needed. What is the type of the *controls* `txt1` and `txt2`? You can't have variables with the same names as controls because the controls are referenced by variables with those names. – Andrew Morton Mar 02 '20 at 12:35
  • 1
    Why would you think that you could access a `Boolean` variable via the `Controls` collection of the form? Are they controls? You can access a control on the form from the `Controls` collection by providing the `Name` property value of the control. It's got nothing to do with variables. If you add a control in the designer then the variable used to refer to it has the same name as its `Name` property but that is just a convenience. They don't have to be the same and won't be if you add controls at run time. `Boolean` values aren't controls and don't have a `Name` property. – jmcilhinney Mar 02 '20 at 13:09
  • 2
    The right way to do what I think you're trying to do is to use an array or a `List` rather than individual variables. You can't access variables by a dynamically-constructed name except by using slow (and ugly) reflection-based approaches. – Craig Mar 02 '20 at 14:47
  • 2
    Maybe you want to add your bool values to a `List(Of Boolean)`. Then use the index to change values in the List. – Jimi Mar 02 '20 at 14:48
  • 1
    Pretty hard to visualize the practicality of a `List(Of Boolean)`. `Dictionary(Of String, Boolean)` would be something useful. You really should share more information about your intent. – LarsTech Mar 02 '20 at 15:27

2 Answers2

1

The right way to access the booleans is in an array or a list.

Using the example of the question:

Dim bool(2) As Boolean

i = i + 1
        If i < 9 Then
            bool(i) = True
        End If
0

I guess you want to iterate over the TextBox controls and then change the property of TextBox.enabled.

You can try the following methods.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each c As Control In Me.Controls
        If c.GetType.ToString() = "System.Windows.Forms.TextBox" Then
            c.Enabled = True 'You can change the TextBox Controls. Enabled to False too.
            c.Text = c.Name.ToString
        End If
    Next
End Sub
Julie Xu-MSFT
  • 334
  • 1
  • 5