Question

i have 5 textbox and i want to call its name with for loop , how to do this :

  textbox1.backcolor = color.Lightblue
  textbox2.backcolor = color.Lightblue
  textbox3.backcolor = color.Lightblue
  textbox4.backcolor = color.Lightblue
  textbox5.backcolor = color.Lightblue

i want to know how to make the code shorter with loop for, so far my only clue is this code :

    Public Sub ShortCode
      For i = 1 to 5
      textbox(i).backcolor = color.lightblue
      Next
    End Sub

any idea how to make this happen ?

Was it helpful?

Solution

Assuming you stick to your naming convention, you don't need to add the text boxes to an array. Use Control.Controls. This function finds controls directly inside some container i.e. Me.Controls searches only the form (Me), not inside containers such as panels and group boxes.

For i = 1 to 5
    CType(Me.Controls("textbox" & i.ToString()), TextBox).BackColor = Color.LightBlue
Next

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controls(v=vs.110).aspx

Similar (not identical) solution in one line with LINQ

Me.Controls.OfType(Of Control).
    Where(Function(c As Control) c.Name.StartsWith("textbox")).
    ToList().ForEach(Sub(c) c.BackColor = Color.Red)

OTHER TIPS

Create an array of your TextBox controls and then iterate over them as you suggested. Below is untested code adapted from http://bytes.com/topic/visual-basic-net/answers/846341-array-textbox, but should get you there.

Dim textboxes As TextBox()
textboxes = New TextBox() {TextBox1, TextBox2, TextBox3};

For i = 1 to 3 
textbox(i).backcolor = color.lightblue

if the answer above doesn't work for you try this

    Public Sub ShortCode
    dim i = 1 
    for i >= 5
     textbox(i).backcolor = color.lightblue
     i = i + 1
    Next

    End Sub

Dim TextBoxBag() As TextBox

TextBoxBag = {TextBox1,TextBox2,TextBox3,TextBox4,TextBox5}

For count = 0 to Ubound(TextBoxBag)

TextBoxBag(count).BackColor = Color.LightBlue

Next

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top