Thabiso Motswagole Thabiso Motswagole - 11 months ago 42
C# Question

How do i make this button's event handler to add multiple values into an array?

My program allows the user to input values of hours and minutes into an array of predefined length.
I want to have this button called add for a form I'm creating to allow multiple inputs from the user until the array is fully inhabited. Then when it's done, to call a sortArray() method They way it is now it only allows one input then it throws an exception. How do I go about this?

private void addButton_Click(object sender, EventArgs e)

int index = 0;


while (index <= array.Length)

minutes = Int32.Parse(minutesTextBox.Text);

hours = Int32.Parse(hoursTextBox.Text);

MessageBox.Show("You have successfully entered a time!");

array[index] = new RandomClass.Time(hours, minutes);

index = index + 1;

catch (Exception ex)
MessageBox.Show("Please only input integer numbers. Start again from the beginning");
hoursTextBox.Text = null;
minutesTextBox.Text = null;
array = null;
arrayLength = null;

MessageBox.Show("Please choose what order you want arrange the sort!");


Answer Source

You haven't shown how large the array is, but this line:

    while (index <= array.Length)

will cause a problem when you get to the end of your array because the indices of an array go from zero to one less than the length of the array.

So you need to change this line to either:

    while (index < array.Length)

It might safer to loop like this:

    foreach (ver element in array)
        // do stuff
        element = new RandomClass.Time(hours, minutes);

as this way there is no way you can loop beyond the end of the array.