NaN
NaN

Reputation: 577

How to dynamically set textbox values in VB6

I would like to dynamically set some textbox values with database values.

I have tried to use something similar to below but I get the following compile error: Can't assign to read only property. The .name = is highlighted.

Is it possible to assign the textbox values in this manner?

Dim x As Integer
 For x = 1 To 30
 Form1.RS.Fields(x).Name = RS.Fields(x).Value
Next

Upvotes: 2

Views: 1301

Answers (3)

Brian M Stafford
Brian M Stafford

Reputation: 8868

As a takeoff on Eddi's answer, here's code that allows for multiple control types on the form:

Dim x As Integer

For x = 1 To 30
   If TypeOf Me.Controls(RS.Fields(x).Name) Is TextBox Then
      Me.Controls(RS.Fields(x).Name).Text = RS.Fields(x).Value
   ElseIf TypeOf Me.Controls(RS.Fields(x).Name) Is CheckBox Then
      Me.Controls(RS.Fields(x).Name).Value = _
         IIf(RS.Fields(x).Value = 1, vbChecked, vbUnchecked)
   End If
Next

One shortcoming of the above code is the loss of intellisense. You can structure the code like the following so it is strongly-typed, which has a number of benefits including intellisense:

Dim tb As TextBox
Dim cb As CheckBox
Dim x As Integer

For x = 1 To 30
   If TypeOf Me.Controls(RS.Fields(x).Name) Is TextBox Then
      Set tb = Me.Controls(RS.Fields(x).Name)
      tb.Text = RS.Fields(x).Value
   ElseIf TypeOf Me.Controls(RS.Fields(x).Name) Is CheckBox Then
      Set cb = Me.Controls(RS.Fields(x).Name)
      cb.Value = IIf(RS.Fields(x).Value = 1, vbChecked, vbUnchecked)
   End If
Next

Upvotes: 2

Étienne Laneville
Étienne Laneville

Reputation: 5031

Assuming you have an array of Text1 textboxes indexed from 1 to 30, you can use:

Dim iCounter As Integer
For iCounter = 1 To 30
   ' Check that counter is within the bounds of the Text1 array
   If iCounter >= Text1.LBound And iCounter <= Text1.UBound Then
       Text1(iCounter).Text = RS.Fields(iCounter).Value
   End If
Next

There's extra code here to check that the counter is within the range of the Text1 array. The Text1 array could be gaps (missing items) in between its LBound and UBound values so it's not perfect. For example you could delete Text1(13) and still have LBound = 1 and UBound = 30. The easiest way is to check for error '340', if you decide to add that. Since you are building the UI you can simply remove any gaps.

Using an array of Textbox controls lets you share common code like the following, which highlights the text when the cursor enters the textbox:

Private Sub Text1_GotFocus(Index As Integer)
    With Text1(Index)
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
End Sub

Upvotes: 1

EddiGordo
EddiGordo

Reputation: 686

You can try using controls collection of the form :

Dim x As Integer
For x = 1 To 30
   Form1.Controls(RS.Fields(x).Name).Text = RS.Fields(x).Value
Next

Upvotes: 2

Related Questions