Tricky : Array of controls dynamically created causing problems

I put "Tricky" in the title because I'm aware that it will be hard to understand precisely what I want but I'll try to be clear.

I have a textBox with an event for TextChange which allow me to create the number of texboxes the user want (we will call it tChange).

Here is a part of the code for this event :

int tester;
bool flag = false;
if (!Int32.TryParse(tChange.Text, out tester))
{
    flag = false;
    return;
}
else
{
    num = Convert.ToInt16(tChange.Text);
    flag = true;
}
if (flag == true)
{
    if (num >= 1)
    {
        for (int i = 0; i < num; i++)
        {
           this.Size = new Size(590, 225 + 105 * i);
           textBoxesQ[i] = new TextBox();
           this.Controls.Add(textBoxesQ[i]);
           textBoxesQ[i].Size = new Size(45, 20);
           textBoxesQ[i].Location = new Point(25, 100 + 100 * i - 1);  
        }
    }
}

So the user enter the value and everything is OK. If he wants to change the number in the tChange, no problem too! The form is resize and the TextBoxes are created. However if he does this (change the value of tChange), everything goes wrong! Errors like

Index out of range

or I can't get the values from the TextBoxes etc..

I started thinking that the TexBoxes were created in front of the previous ones and the error came from this, so I tried to put the new ones to front, bring the old ones to front but none worked..

textBoxesQ[i].BringToFront();
textBoxesQ[i].SendToBack();

I also tried to delete the old ones before creating the new but I think that my code was wacky and it didn't work at all.

textBoxesQ[i].Dispose();

EDIT : As @Dr. Stitch said, It may come from not reinitializing the TextBoxes each time the text in tChange is changed. Now I just need to figure out how to make it happen.

Jon Skeet
people
quotationmark

You need to do three things when the number changes:

  • Remove any existing textboxes
  • Create a new array with the new size, and save a reference to that new array into your field (textBoxesQ)
  • Initialize the array

So something like:

if (textBoxesQ != null)
{
    foreach (var textBox in textBoxesQ)
    {
        Controls.Remove(textBox);
    }
}
textBoxesQ = new TextBox[size];
for (int i = 0; i < size; i++)
{
    var textBox = new TextBox
    {
       Size = new Size(45, 20);
       Location = new Point(25, 100 + 100 * i - 1);  
    };
    Controls.Add(textBox);
    textBoxesQ[i] = textBox;
}

people

See more on this question at Stackoverflow