Search code examples
c#arrayswinformsuser-controls

Making an indexed control array?


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.


Solution

  • As I mentioned in comment to a solution by HatSoft, C# Winforms does not allow you to create control arrays like old VB6 allowed us. The nearest I think we can get to is what HatSoft and Bert Evans in their posts have shown.

    One thing that I hope would satisfy your requirement is the event handler, you get a common event handler and in the event handler when you typecast the "sender" you get the control directly just like you would in VB6

    C#

    TextBox textBox = sender as TextBox;
    

    VB6

    TextBox textBox = TextBox1[i];
    

    So the only trouble you might have is wiring those 100 TextBoxes to a single event handler, if you are not creating the controls dynamically through code rather creating it manually at design time then all one can suggest is group them in a container like say Panel. Then on Form Load wire them all up to a single event handler like this:

    foreach (Control control in myTextBoxPanel.Controls)
    {
        if(control is TextBox)
             control.TextChanged += new EventHandler(control_TextChanged);
    }