-1

I have the following code example:

public int intTest { get; set; }
public List<int> listTest { get; set; }

//Method for creating a random number to return.
public int methodRandom()
{
    Random random1 = new Random();
    int intValue;
    intValue = random1.Next(1, intTest + 1);
    return (intValue);
}

private void button1_Click(object sender, EventArgs e)
{
    intTest = int.Parse(textBox1.Text); // Will be a value between 1 and 9 in my code)
    for (int i = 0; i < intTest; i++)
    {
        int temp = methodRandom();
        listTest.Add(temp);
    }
}

But when I debug and I click the button, I get the following Error message marking the "listTest.Add(temp);" saying "NullReferenceException was unhandled". What do I do wrong?

user3501058
  • 21
  • 2
  • 4
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dour High Arch Apr 09 '14 at 16:25

2 Answers2

0

You have to instantiate the list before you can add items to it. Your constructor's a good place for that.

public YourClass()  // I don't know what the name of your class is.
{
    listTest = new List<int>();
}

You'll probably want to clear the list each time the button1_Click event fires too (unless your intention is to just keep adding numbers to the list).

private void button1_Click(object sender, EventArgs e)
{
    listTest.Clear();  // Clear previous items before adding new ones

    ...
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0
private void button1_Click(object sender, EventArgs e)
{
    listTest=new List<int>();
    intTest = int.Parse(textBox1.Text); // Will be a value between 1 and 9 in my code)
    for (int i = 0; i < intTest; i++)
    {
        int temp = methodRandom();

        listTest.Add(temp);
    }
}
huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99