简体   繁体   中英

add textbox number to array c#

I'm trying to make this program where a user will input a number in a textbox and it will store it into an array.

So whenever the user clicks "calculate", it will get an average of all the numbers in the array. For some reason, when I try to run it, I get:

Additional information: Object reference not set to an instance of an object.

But then I can't initialize the array to specific length because I don't know how many numbers the user will input. So I was wondering is there a way to make it work without initializing a specific length for the array?

double[] numArray;
int count=0;

private void button1_Click(object sender, EventArgs e)
    {
        numArray[count] = convert.ToDouble(textBox1.Text);
        count++;
        displayNum.Visible = true;
        displayNum.Text = count.ToString();
         ;
    }

Why are you using array if you don't know the size? Use list instead.

Initialization:

List<double> numList = new List<double>();

Adding to list:

numList.Add(some_element);

Use a IList/List as these start off with a size but if you fill it up they will automatically grab more memory and grow.

IList<double> numArray = new List<double>(); 
int count=0;

private void button1_Click(object sender, EventArgs e)
{
    numArray.Add(convert.ToDouble(textBox1.Text));
    count++;
    displayNum.Visible = true;
    displayNum.Text = count.ToString();
}

This is not possible with an array. An array needs to be initialized with the number of array items. Instead of an array I would suggest using List . This way you can add to the list without the restriction of defining how many items will be in it. If you need an array after you populated the I believe there is a ToArray method off of List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM