eraser2220 eraser2220 - 9 months ago 38
C# Question

Declare and Initialising array of Checkboxes in other class (not Form1)

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;
}
}

Answer Source

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;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download