Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 537
raven Avatar asked Sep 02 '08 13:09

raven


2 Answers

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;
}
like image 107
Seb Nilsson Avatar answered Sep 18 '22 05:09

Seb Nilsson


Another nice thing that VB .NET does is having a single event handler that handles multiple controls:

Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ 
        Handles TextBox1.TextChanged, _

        TextBox2.TextChanged, _

        TextBox3.TextChanged

End Sub
like image 26
Mark Biek Avatar answered Sep 21 '22 05:09

Mark Biek