What is the best way to access things on a form from another form? C #

advertisements

I was just wondering. If I have two forms.. Form 1 and Form 2 and you need to access a textbox, a label etc.. for example to make it visible or to change its text..

Which is the best way to access these from Form2?

Making a method in Form 1 like:

public void setTextBoxVisible(){
     textBox1.Visible = true;
}

or making an accessor in Form 1, and change the visibility from Form 2, like:

In Form 2:

public TextBox TextBox1 {
    get { return textBox1; }
}

In Form 1:

Form1 form1 = new Form1();
form1.TextBox1.Visible = true;

I know it may be a stupid question but I am still new to programming and I wish to know the best way I could do these things. Thanks :)


Option 1 is definitely better, because you are only exposing the part that you want to expose.
Not only are you leaving less room for error on part of the caller, but you are stating the intent of your method.

In option 2, all aspects of your control are accessibly and can be changed from outside code, not only the Visible property.

You could, if it suits your preference better, create a property:

public bool TextBox1Visible
{
    get { return TextBox1.Visible; }
    set { TextBox1.Visible = value; }
}