2

I wonder if anyone can help me with the following please?

I have 20 labels on my form, named "Name1", "Name2" etc..... I want to read from a DB and populate each label with its corresponding value from the DB row.

At the moment the code does this the long way:

Name1.Text = dt.Rows(0).Item("Name1")
Name2.Text = dt.Rows(0).Item("Name2")
etc.....

I want to use an array and a loop to reduce the code, but I'm not sure what I need to do. The below works perfectly, apart from instead of Name1.Text I actually want it to be Name(i).text = ....... Suffice to say this doesn't work, so I'd like to know what I'm doing wrong.

For i As Int16 = 1 To 20
    Name1.Text = dt.Rows(0).Item("Name" & (i))
Next

Thank you,

Jonny Mccoy
  • 21
  • 1
  • 2

1 Answers1

0

You could add the controls you want in an array (in the correct order). Then use a For or For Each loop to iterate.

With your code it looks like :

Dim textBoxes() As TextBox = {Name1, Name2, Name3, Name4, Name5, etc}
For i As Int16 = 0 To textBoxes.Count -1
    'According To Matt Wilko, it's better to start from 0 to textBoxes.Count-1, so you'll have to use i+1
    textBoxes(i+1).Text = dt.Rows(0).Item("Name" & (i+1))
Next

By the way, i'm not sure this is the best way :/

nbadaud
  • 694
  • 7
  • 26