Question

I'm trying to update the value of a checkbox inside a flowlayoutpanel in c#. The checkboxes are generated for each panel that is created and are named "selected1".

To try and access a specific checkbox in code I'm using

flowLayoutPanel2.Controls[e.Index].Controls["selected1"]

I've tried to create a CheckBox object and get the Name property as the value and get an error stating:

System.NullReferenceException: Object reference not set to an instance of an object.

The code I'm using is:

try
{
    System.Windows.Forms.Control checkBox = new System.Windows.Forms.Control();
    checkBox = flowLayoutPanel2.Controls[e.Index].Controls["selected1"];
    MessageBox.Show(Convert.ToString(checkBox.Name));
}
catch (Exception ex)
{
    MessageBox.Show(Convert.ToString(ex));
}

I think I'm probably just trying to access the checkbox in the wrong way, as if I just try to access the panel enclosing it I can manipulate the panel with no problems.

Thanks, Sam

Was it helpful?

Solution

It's not clear where e.Index is coming from, but I don't think it's necessary:

CheckBox checkBox;
if (flowLayoutPanel2.Controls.ContainsKey("selected1")) {
  checkBox = (CheckBox)flowLayoutPanel2.Controls["selected1"];
}

If you are interested in the value, it's probably best to use CheckBox instead of just Control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top