I have a basic form with a button and a textbox to insert a number
I want to keep the number inserted in the first index of the array, then if I put another number and I click the button, I want that number to be stored in the second index of the array and so on
I have to make a loop to increment the index but if I use the loop, the first number I put in the box, it's going to be stored in all the indexes of the array
Here's my code (doesn't work)
public partial class EXERCISES_ARRAYS : Form
{
int[] numbers = new int[5];
private void btnAdd_Click(object sender, EventArgs e)
{
int i = 0;
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
for (int j = 0; j < 5; j )
{
numbers[i] = insertedNumber;
i ;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
}
}
CodePudding user response:
You want a List, rather than an array. That will take care of all of this for you:
public partial class EXERCISES_ARRAYS : Form
{
List<int> numbers = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
numbers.Add(int.Parse(txtInsertedValue.Text));
}
}
CodePudding user response:
I don't think you need to add a for loop for this. Try this
int[] numbers = new int[5];
int i = 0;
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
numbers[i] = insertedNumber;
i ;
if (i == 5)
{
btnAdd.Enabled = false;
}
}