Fill vector with TextBox in C #

0

I'm trying to fill in the positions of a vector with incoming data coming of a TextBox, and do the reading in a ListBox but I'm not getting it. Everything seems to work, but only inserts the last element in all positions of the vector.

Code snippet:

int a = 0, i = 0;
private void okClick(object sender, System.EventArgs e)
{
   //a incrementa à cada click do botão
   a++;
   int[] arr = new int[5];
   for (i = 0; i < (arr.Length); i++)
   {
      arr[i] = Int32.Parse(textBox.Text);
   }
   //limpa o campo do TextBox a cada novo click do botão
   textBox.Clear();
   //Quando a recebe o quinto clique imprime.
   if (a == 5)
   {
      for (i = 0; i < arr.Length; i++)
      {
         listBox.Items.Add(arr[i]);
      }
   }
}
    
asked by anonymous 21.10.2018 / 00:48

1 answer

1

Hello @endrew_lim, note that every time you instantiate the object int[] arr = new int[5]; , instantiating this object it initializes empty, then you include a value and when it prints it always contains only the last value entered. You should instantiate this array before the click event, do it on the same line where you declared the variables a and i .

See how it goes: Take the test, if it works, mark it as the correct answer;)

int a = 0, i = 0;
int[] arr = new int[5];

    private void ok_Click(object sender, EventArgs e)
    {
        arr[a] = int.Parse(textBox.Text);
        //limpa o campo do TextBox a cada novo click do botão
        textBox.Clear();
        //Quando a recebe o quinto clique imprime.
        if (a == 4)
        {
            for (i = 0; i < arr.Length; i++)
            {
                listBox.Items.Add(arr[i]);
            }

            ok.Enabled = false;
        }

        a++;
    }
    
21.10.2018 / 03:06