0

I have a WinForm with only 2 CheckBoxes on it, and firing an event, when CheckedChanged. Now....this Event calls a Method from an other Class, where i try to assign the value of the event-firing method to an checkboxarray with index of [0].

But i get always a "NullReferenceException" when the new initialized CheckBoxArray gets a Value.....why ist that so ??? Here is my Code:

public partial class Form1 : Form
{   
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.checkBox1.CheckedChanged += 
            new EventHandler(new DoSomething().FromForm1Class);
    }
}

class DoSomething
{
    CheckBox[] mycheckboxes = new CheckBox[2];

    public void FromForm1Class(object sender, EventArgs e)
    {
        CheckBox n = sender as CheckBox;

        mycheckboxes[0].Checked = n.Checked;
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

2 Answers2

3

In class DoSomething you are declaring an Array of CheckBoxes, but you do not initialise each element in the Array. That is why you get a NullReferenceException, because the 0th element is null - it is not a Checkbox! So you need:

class DoSomething
{
    CheckBox[] mycheckboxes = new CheckBox[2];

    public DoSomething()
    {
         mycheckboxes[0] = new CheckBox();
         mycheckboxes[1] = new CheckBox();
    }

    public void FromForm1Class(object sender, EventArgs e)
    {
        CheckBox n = sender as CheckBox;

        mycheckboxes[0].Checked = n.Checked;
    }
}
Jonathan Willcock
  • 5,012
  • 3
  • 20
  • 31
0

U are missing initialization

public partial class Form1 : Form
{   
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.checkBox1.CheckedChanged += new EventHandler(new DoSomething().FromForm1Class);
    }
}

class DoSomething
{
    CheckBox[] mycheckboxes = new CheckBox[2]{new CheckBox(), new CheckBox()};

    public void FromForm1Class(object sender, EventArgs e)
    {
        CheckBox n = sender as CheckBox;

        mycheckboxes[0].Checked = n.Checked;
    }
}
Ramankingdom
  • 1,478
  • 2
  • 12
  • 17