Home > Enterprise >  Adding value from dynamically created textboxes into array (windows forms)
Adding value from dynamically created textboxes into array (windows forms)

Time:11-16

im making a project for university, for which i use windows forms. i have to create a program, where you can generate an several amount of textboxes and calculate all values. the calcutation is about the sum and average of every value combined. therefore i have two buttons, one to create the textboxes and another one to do the calculation (doTheMath_Click). heres my code so far: button for the calculation:

private void doTheMath_Click(object sender, EventArgs e) 
{ 
        int radius = int.Parse(numberofnumbers.Text)
        int sum = 0;

        for (int i = 0; i < zahlen.Length; i  )
        {
            sum  = numbers[i];
        }
        double average = (double)sum / (double)radius;
        total.Text = sum.ToString();
        averagee.Text = average.ToString();;

 }

int newtextboxn = 8;    
int alingment = 200;

public TextBox addnewtextbox() 
{
        TextBox textbox = new TextBox();
        this.Controls.Add(textbox);

        if (newtextboxn % 18 == 0)
        {
            alingment  = 200;
            newtextboxn = 8;
            textbox.Top = newtextboxn * 27;
            textbox.Left = alingment;
        }
        
        else
        {
            textbox.Top = newtextboxn * 27;
            textbox.Left = alingment;
        }
        newtextboxn = newtextboxn   1;
        return textbox;
    }

button to print the textbox:

public void printTextbox(int radius) 
{   
    for (int i = 0; i < radius; i  )
    {
        addnewtextbox();
     }
}

private void printTheBox_Click(object sender, EventArgs e) 
{
    int radius = int.Parse(numberofnumbers.Text);
    printTextboxandLabels(radius);
}

I had the idea to save the values of the textboxes in an array, but i dont know if it would work, because the array length should also be dynamically and i also dont know, how to initialize the array in the end. My other idea was to save the values in a list, but theres the same problem about the initialization. i hope, that my problem is understandable and that you can help me. i already surfed around stackoverflow, but i didnt found an idea to solve my problem. thx

CodePudding user response:

Just create a List where you store the created set of textboxes. Then you can use the code to loop over this list and retrieve the content of each textbox.

 List<TextBox> textboxslist = new List<TextBox>();

and inside addnewtextbox() method fill textboxlist using The Add method.

textboxlist.Add(textbox);

then inside loop code in doTheMath_Click button you can access the values of each textbox by using Text Property.

 for (int i = 0; i < textboxlist.Count; i  ) {
   int textboxvalue = int.Parse(textboxlist[i].Text);
   sum  = textboxvalue;
 }
  • Related