I am new to this forum and this is my first post.
I am working on a C# project. General outline of the project is:
FORM 1 collects data as entered by the user (in text boxes, radio buttons, check boxes, numeric up-down controls etc) .
FORM 1 then does some calculations using this data and prepares a text message. I have a class created to do this job and updated Message is with the Class.
FORM 2 should take this text message and display it using a Rich text box.
User typically opens FORM 2 as and when it is needed to see the Message. User can kill/minimize FORM 2 . There is a button on FORM 1 to show FORM 2.
FORM 1 must update the FORM 2 whenever a new Message is generated provided FORM 2 is already instanced ( either showing or in minimized state.)
When FORM 2 is instanced by FORM 1 it must get the message from Form 1, so that upon instancing the FORM 2 shows the latest message from FORM 1.
I have coded something which worked , but I am a bit skeptical about the approach. Please guide me.
What I am doing is:
FORM 2 which displays the Message string, is instanced as:
public string messageIn;
public FORM2(string myMessage)
messageIn = myMessaage; // input string to on FORM public variable
In FORM 2 I have a public method:
public void ShowMessage(messageIn)
I call this ShowMessage in the form_load method:
private void FORM2_Load(object sender, EventArgs e)
{
ShowMessage(messageIn);
}
In FORM 1 , have to call this ShowMessage in FORM 2 so that update message gets displayed on FORM 2.
There are two possibilities:
1> FORM 2 is not yet instanced : I shouldn't care to update it.
2> FORM 2 is already instanced.I must update FORM 2
So check that part first as:
bool IsOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == "FORM2")
{
IsOpen = true; // FORM found
break;
}
} // Loop to check next FORM
// If FORM2 is already instanced then and then only update
// If FORM2 is not instanced , no need to update
if (IsOpen == true)
{
// FORM2 already instanced , OK to update it
FORM2 f1 = (FORM2)Application.OpenForms["FORM2"];
f1.ShowMessage(message);
}
When user Clicks on the button on FORM 1 to view message, I check first the whether the form is already instance or not.
If it is there already, I call the the method in FORM 2 as shown above, else I instance the FORM 2 as:
FORM2 frm2 = new FORM2(message);// message goes as FORM2 constructor input argument
frm2.Show();
I am a bit worried about using:
FORM2 f1 = (FORM2)Application.OpenForms["FORM2"];
Is it safe (legitimate)/ good practice or it might pose some potential problems later?
Or is there any better / clean way of doing this?
Regards
Babali