Opening Forms

Weste

Newcomer
Joined
Feb 4, 2005
Messages
14
I have 3 Forms - Form1, Form2, and Form3. Both Form1 and Form2 have a button to open Form3. Form3 displays differently depending on whether Form1 or Form2 opened it. What i the best way using C# to determine which form opened Form3? Thanks for the help!

Weste
 
Just add a new constructor to Form3 that takes a Form instance as a parameter:
C#:
public Form3(Form form)
{
    if (form is Form1)
    {
        // opened by Form1
    }
    else if (form is Form2)
    {
        // opened by Form2
    }

    InitializeComponent();
}
You can then create a new instance of Form3 like:
C#:
Form3 form3 = new Form3(this);
form3.ShowDialog();
 
It would be ideal to make a better representation of your intent with you code. I don't know what Form1, Form2, and Form3 do--their names are not descriptive of their function--so it is hard to give a particularly relevant example, but Form3's constructor could take a boolean to indicate whether or not a certain type of information is displayed or an enumeration that indicates how to present data and input controls. For the sake of an example, let's say that Form1 should open Form3 and to present data as read-only and Form2 should open Form3 to present editable data.
C#:
// Form3's constructor accepts a boolean to indicate whether or not data may be edited
public Form3(bool AllowEditing){
    InitializeComponent();
  
    // Initialization regarding editability goes here
}
Now someone else, or you a year down the road, can understand what the meaning of the constructor's parameter is. Form1 and Form2 can open Form3 as follows:
C#:
//Within Form1
public void ShowForm3(){
// Show Form3 as readonly.
    Form3 displayForm = new Form3(false); 
    displayForm.ShowDialog();
}
 
// Within Form2
public void ShowForm3(){
// Show Form3 and allow editing.
    Form3 displayForm = new Form3(true); 
    displayForm.ShowDialog();
}
Another advantage beyond readability is reusability. If you need to show Form3 from somewhere else (a UserControl or a DLL that doesn't own any forms) you don't need to pass a Form to the constructor, whereas using the other method the constructor expects an instance of Form1 or Form2.

I'm not telling you to change the code you've already written, just something to consider next time you have to make a design choice.
 
Back
Top