Fill vector with Textbox in C#

Asked

Viewed 444 times

0

I’m trying to fill the positions of a vector with data input 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 vector positions.

Excerpt from the code:

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]);
      }
   }
}
  • Welcome to Stackoverflow Endrew. In this code you are trying to convert control text TextBox in an integer, and you play the result of this in the 5 occurrences of your array (yes, the same value in the 5 occurrences of the array). What exactly do you want to do?

  • I type a number in the Textbox and click on the ok button. Meanwhile the integer variable "a" is incremented, with the click of the button. What I want is for each number inserted in the Textbox to enter the array positions. Ex: if I type 10, in the Textbox, it enters in the arr [ 0 ] position of the array, if I then type 20, let it enter in the arr [ 1 ] position of the array, and so on until it completes the operation.

1 answer

1


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

Here’s how it looks: 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++;
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.