What's the simplest .NET equivalent of a VB6 control array?

raven picture raven · Sep 2, 2008 · Viewed 11.8k times · Source

Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):

Private Sub Command1_Click(Index As Integer)

   Text1(Index).Text = Timer

End Sub

I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6. What is the simplest equivalent in C# or VB.NET?

Answer

Seb Nilsson picture Seb Nilsson · Sep 2, 2008

Make a generic list of textboxes:

var textBoxes = new List<TextBox>();

// Create 10 textboxes in the collection
for (int i = 0; i < 10; i++)
{
    var textBox = new TextBox();
    textBox.Text = "Textbox " + i;
    textBoxes.Add(textBox);
}

// Loop through and set new values on textboxes in collection
for (int i = 0; i < textBoxes.Count; i++)
{
    textBoxes[i].Text = "New value " + i;
    // or like this
    var textBox = textBoxes[i];
    textBox.Text = "New val " + i;
}