Working with controlls on different forms

Hello.

I have 2 forms. On form1 I have a button and on form2 I have a checkbox. When I press the button on form1 I want to check the checkbox on form2. Of course, assume that the checkbox form has already been shown. I am really stuck on this. Any ideas !



Answer this question

Working with controlls on different forms

  • exo_duz

    Just be sure you note that if you have multiple copies of F2 open, this will not work. This technique works well if you know you only have one copy of that form open.

  • David Pinero

    yes make the checkbox on form 2 public.. you can do that by modifing manually the form2.designer.cs or in the Propreties windows at the Design tab set modifiers to public

    acessing the checkbox from form1

    1)make a instance of form2
    Form2 form2=new Form2();
    2)modifing the checkbox
    form2.checkBox1.Checked=false;


  • Chad Bumstead

    Hello

    There is a simple solution exits for it

    in the Button Click Event of Form1 , write the following code

    private void button1_Click(object sender, EventArgs e)
    {
    Form2 f2 = (Form2)Application.OpenForms["Form2"];
    f2.checkBox1.Checked = true;

    }

    this will return the current running instance of Form2, and then checked the checkbox, make sure that the checkbox is public.

    Hope this might help


  • j_ruez

    Thank you guys. You really saved my ***.
    Cheers

  • Dennis Micheelsen

    exactly what i sad .. only that he gives you some sample


  • stir

    You can better create a property on your Form2 to encapsule it.


    public class Form2 : Form
    {
    private CheckBox _chkPriorityShipment;

    public bool PriorityShipment
    {
    get
    {
    return _chkPriorityShipment.Checked;
    }
    set
    {
    _chkPriorityShipment.Checked = value;
    }
    }
    }



    Now, you only have one extra property and nobody can set the checkbox like when you just using the public modifier. Using the public modifier has a lot of side effects, every property can be set of the checkbox outside when you make him public. Or even worse, it can be initialized outside!
    So use a property to encapsule it.

    Usage:

    private void button1_Click(object sender, EventArgs e)
    {
    Form2 form = (Form2)Application.OpenForms["Form2"];
    form.PriorityShipment = true;

    }




  • Working with controlls on different forms