Making an indexed control array?

Viewed 23075

Has C# indexed control arrays or not? I would like to put a "button array" for example with 5 buttons which use just one event handler which handles the index of all this 5 controls (like VB6 does). Else I have to write for each of these 5 buttons one extra event handler. And if I have 100 buttons, I need 100 event handlers? I mean something like that:

TextBox1[i].Text="Example";

It could make coding definitely easier for me to work with control arrays. Now I have seen, that C# at least has no visible array functionality on user controls and no "index" property on the user controls. So I guess C# has no control arrays, or I must each element call by known name.

Instead of giving 100 TextBoxes in a for loop 100 incrementing values, I have to write:

TextBox1.Text = Value1;
TextBox2.Text = Value2;
...
...
TextBox100.Text = Value100;

A lot of more work + all these 100 event handlers each for one additional TextBox extra.

7 Answers

Keeping it simple:

TextBox[] keybox = new TextBox[16];   //create an array

for (int i=0; i<16; i++) 
{
    keybox[i] = new TextBox();        //initialize (create storage for elements)
    keybox[i].Tag = i;                //Tag prop = index (not available at design time)
    keybox[i].KeyDown += keybox_down; //define event handler for array
}

private void keybox_down(object sender, KeyEventArgs e)
{
    int index = (int)((TextBox)sender).Tag    //get index of element that fired event
    ...
}
Related