show the second form?

Frosty_J

New member
Joined
Jul 1, 2013
Messages
2
Programming Experience
1-3
In Visual C# Express 2010
Win32 Environment

I designed two forms, both standard windows forms. How do I show the second form by clicking a button on the first form?

private Form2 otherForm = new Form2();

isn't necessary, is it? The forms are already designed... so I don't need a new instance

Also, since this seems to be more complicated than I expected, how would I access controls across forms? So far I have seen to change Modifiers property to public, but haven't got as far as the code yet.
 
Of course you need a new instance. If someone at a car company designs a new car, does that mean that we can all start driving it? Of course not. They have to build many cars based on that design so that many people can buy and drive it. Your forms are the same. The design is a class, not an object It's a class and, just like every other class, you have to instantiate it to make objects of that type.

As for accessing controls, forms are just like any other objects so you access their data like any other object. Each control has a field (member variable) declared that refers to it. You can create a String and access its Length property, right? Creating a form and accessing its TextBox1 field is no different.

That said, accessing controls directly from outside the form is bad practice. That's why those fields are private by default. A form should provide an interface of properties and/or methods and you use those to interact with it from the outside, while it interacts with its own controls internally. For instance, let's say that you have a Label on Form1 and you want to edit its contents in a TextBox in Form2. You would declare a property in Form2 to expose the contents of the TextBox:
public string TextForEditing
{
    get { return textBox1.Text; }
    set { textBox1.Text = value; }
}
You would then use that property in Form1 to get data into and out of an instance of Form2:
private void button1_Click(object sender, EventArgs e)
{
    using (var dialogue = new Form2())
    {
        // Pass the input data to the dialogue.
        dialogue.TextForEditing = label1.Text;

        // Display the dialogue.
        dialogue.ShowDialog();

        // Get the output data from the dialogue.
        label1.Text = dialogue.TextForEditing;
    }
}
You could then completely change the method of editing in Form2 and nothing would change in Form1. Form1 doesn't know or care anything about what's inside Form2. Moreover, Form2 doesn't even know or care that Form1 exists. This is known as loose coupling, where each class relies on as little as possible in other classes.
 
ok, thank you for the car metaphor to clear things up. I'm coming from old-skool VB programming and more recent console C++ apps. I understand the concept, was just unclear on the specific C# terminology/usage.
 
Back
Top Bottom