0

When I try to add to a list that I declared at the start of the file it says gives a null reference exception.

I have this at the start of the code:

namespace YTDL
{
    public partial class options : Form
    {
        public List<string> output;
        public List<RadioButton> radioButtons;
        public RadioButton checkedButton;

then I have this method

public void updateRdio()
{
    if (output != null)
    {
        for (int i = 7; i < output.Count(); i++)
        {                   
            radioButtons[i] = new RadioButton();
            radioButtons[i].Text = output[i];
            radioButtons[i].Location = new System.Drawing.Point(10, 30 + (i - 7) * 30);
            radioButtons[i].Name = "radioButton" + i.ToString();
            radioButtons[i].AutoSize = true;
            this.Controls.Add(radioButtons[i]);
            Console.Write(output[i]);
        }
    }
}

when I run it it breaks and highlights the lines that use "radioButtons" and says null reference error.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
n3wton
  • 35
  • 6

1 Answers1

2

You have to initialize this list before adding elements to it:

radioButtons = new List<RadioButton>();

for (int i = 7; i < output.Count(); i++)
{                   
    radioButtons[i] = new RadioButton();
    radioButtons[i].Text = output[i];
    radioButtons[i].Location = new System.Drawing.Point(10, 30 + (i - 7) * 30);
    radioButtons[i].Name = "radioButton" + i.ToString();
    radioButtons[i].AutoSize = true;
    this.Controls.Add(radioButtons[i]);
    Console.Write(output[i]);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928