Click here to Skip to main content
15,868,019 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
for example if i create new form

C#
Form3 f3 = new Form3();
using "f3." you can access the form


but with the default one, for example when you start new project the form1, how do you access it other by this keyword?

this not always points to the current form, so what is the best and most precise way to access the form?

for example you open new project and programatically how do you change the form's text?
solution one is:
C#
this.Text = "example";
Posted
Updated 28-Nov-14 5:49am
v2

There is no "default form" as such - there is just the one instance that is created in the
Main method:
XML
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new frmMain());
    }
Which you will find in the "program.cs" file.
AFAIK, it isn't specifically stored anywhere (though you could pick it up from the Application.OpenForms property, I wouldn't want to rely on it being the first item in the collection myself).
Other than that, there is nothing special about it - it's just an instance of the form that will close the app when it closes.

Why would you want to change the Text from outside the instance anyway?


"so basically i access the default form1 by using Form1.ActiveForm.Text to change it?
by the way i just used the text option just for example like i said..."


Well...no.
Form.ActiveForm returns the currently active form for the application (the last one to receive the focus) which may not be an instance of Form1 at all - it could be a form you created in Form3!

And doing things that way is not a good idea - because it tends to end up with unpredictable and intermittent bugs which are a complete PITA to find in six months time when someone notices. Or a horrible error because you forgot about it and changed something else! Plus, it's very much against the principles of OOPs - because you have to make forms "know" about each other which means they are hard to reuse.

The better way to do this is to create a new event in the form which is handled in it's "parent" - and that form then deals with it. That is better design from an OOPs POV, because the "parent" already has to know the "child" exists because it creates instances of it, but the child doesn't have to know what it's "parent" is, or even if there is a parent! All it does it signal the event and if there is a handler, it gets to do what it has to do.

It sounds complicated, but it's really very simple to do: Transferring information between two forms, Part 2: Child to Parent[^] will show you how.
 
Share this answer
 
v2
Comments
SrgjanX 28-Nov-14 12:31pm    
so basically i access the default form1 by using Form1.ActiveForm.Text to change it?
by the way i just used the text option just for example like i said...
OriginalGriff 28-Nov-14 14:15pm    
Answer updated.
In a Windows Forms Application created in the standard way:

1 in the static Program.cs Class

2. a static 'Main method is executed which

3. calls 'Application.Run with

4. a new instance of a Form definition, the "main form," as its parameter.

There is no Application wide reference available to that instance of the "main form."

You can get a Collection of all currently open Forms in the running Application using:
C#
private void btnShowMeTheOpenForms_Click(object sender, EventArgs e)
{
    var openForms = Application.OpenForms;

    for (int i = 0; i < openForms.Count; i++)
    {
        var f = openForms[i];

        MessageBox.Show(string.Format("{0} {1}", i, f.Name));
    }
}
While it will almost certainly be the case that the first (#0 index) in that FormCollection will be the "main form," I think it's always dangerous to rely on such an assumption.

So, you want an Application-wide reference to the main form: in your main Form's constructor:
C#
public static Form MainForm;

public YourMainForm()
{
    InitializeComponent();
    
    MainForm = this;
}
You can then use YourMainForm.MainForm anywhere in any Form you created to get a pointer to the main form.

And, now, I'm going to tell you why you should not do this: by exposing your main form you are potentially allowing side effects ... through manipulation of any (objects) public fields, properties, methods in the main form: this is like leaving your house unlocked in a high-crime neighborhood with your money and keys in plain sight through the windows ... and other programmers will shun you if you do this, muttering something about a "smell" :)

What you should do to have that fresh-all-over-mint-feeling is carefully decide what objects on/in your main form you absolutely must expose to any other secondary forms.

My bias is that you should strive to never expose anything on a main form to a secondary form: that secondary forms should be dumb as logs, and themselves expose the minimum necessary to "outside entities," like the main form, or any other secondary form.

imho the figuring out the specific implementation for passing data/objects from one form to another is best dealt with ... for beginning students of .NET ... by focusing on specific programming tasks in prototype applications: there are several useful techniques that have become almost conventional.

If you post more specifics about your requirements for main form <=> secondary form interchange, I will respond.

The special keyword 'this will always return a reference to the current context (the instance of) the run-time object it is used in.
 
Share this answer
 
v2
The this keyword is used to reference the current object when using the methods of the object's class; it is not specific to Windows.Forms (which are just C# classes). You refer to any other object by its reference like:
C#
// in Form1 class
void Form1_method()
{
    this.property = 1; // this refers to form1's property field
    f3.Form3_method(this); // pass reference to Form1 to a method of Form3
}

...


// in Form3 class
void Form3_method(Form otherForm)
{
    this.property = 1; // this refers to form3's property field
    otherForm.Method(); // call the method of the 'other' form.
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900