Smanyx
asked on
Windows Forms: One instance not multiple instances of a Form
Hi There,
I am trying to build a Windows Form application with multiple forms. I want to be able to open a form from many different places or options like from a menu bar, a toolbar etc... and from any of the forms. How can I do to make sure that from wherever the form is being accessed, one and only one copy of the form is display not several instances of the same form?
Thank you!
Smanyx
I am trying to build a Windows Form application with multiple forms. I want to be able to open a form from many different places or options like from a menu bar, a toolbar etc... and from any of the forms. How can I do to make sure that from wherever the form is being accessed, one and only one copy of the form is display not several instances of the same form?
Thank you!
Smanyx
Hi Smanyx;
Microsoft Patterns & Practices
Implementing Singleton in C#
You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.
http://msdn.microsoft.com/en-us/library/ms998558.aspx
Fernando
Microsoft Patterns & Practices
Implementing Singleton in C#
You are building an application in C#. You need a class that has only one instance, and you need to provide a global point of access to the instance. You want to be sure that your solution is efficient and that it takes advantage of the Microsoft .NET common language runtime features. You may also want to make sure that your solution is thread safe.
http://msdn.microsoft.com/en-us/library/ms998558.aspx
Fernando
Here's a simple example of a singleton as suggested by Fernando:
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
ASKER
Thanks for your reply,
I am fairly new to the world of Windows Forms programming and C#. I read the article in the link you provided but still can't figure out how to implement any of the examples given.
I thought, I'd post the code I have so far from one Form, that way you could guide me on how to implement the Singleton class, for example
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
with this existing code.
Smanyx
I am fairly new to the world of Windows Forms programming and C#. I read the article in the link you provided but still can't figure out how to implement any of the examples given.
I thought, I'd post the code I have so far from one Form, that way you could guide me on how to implement the Singleton class, for example
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
with this existing code.
Smanyx
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public partial class Form2 : Form
{
//declaring form variables
Form4 fourthForm;
Form3 thirdForm;
Form2 secondForm;
Form1 firstForm;
public Form2()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void classToolStripMenuItem_Click(object sender, EventArgs e)
{
//creating a new object
thirdForm = new Form3();
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
//creating a new object
secondForm = new Form2();
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout;
frmAbout = new AboutBox1();
frmAbout.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
//creating a new object
fourthForm = new Form4();
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
//creating a new object
thirdForm = new Form3();
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
}
}
}
Hi Smanyx;
In Form2 below I have made it a Singleton. Please read all the comments I have placed in it. Also because FormName.Instance returns a reference to the form these lines were removed:
//declaring form variables
Form4 fourthForm;
Form3 thirdForm;
Form2 secondForm;
Form1 firstForm;
I also needed to add one event to make the Singleton pattern work correct with a form, see FormClosing event below.
Fernando
In Form2 below I have made it a Singleton. Please read all the comments I have placed in it. Also because FormName.Instance returns a reference to the form these lines were removed:
//declaring form variables
Form4 fourthForm;
Form3 thirdForm;
Form2 secondForm;
Form1 firstForm;
I also needed to add one event to make the Singleton pattern work correct with a form, see FormClosing event below.
Fernando
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
// Modify this line for the Singleton pattern
public sealed partial class Form2 : Form
{
// Add this line for the Singleton pattern
private static readonly Form1 instance = new Form1();
// Modify this line for the Singleton pattern
private Form2()
{
InitializeComponent();
}
// Add this line for the Singleton pattern
public static Form1 Instance
{
get { return instance; }
}
// Add this event to the form for the Singleton pattern. This is needed because
// if a user clicks on the X in the upper right of the form the form will be
// Disposed making the read only property instance invalid which will make the
// next call to the form an invalid call.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// We hide the form and set e.Cancel to true so that we do not dispose of the form
this.Hide();
e.Cancel = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void classToolStripMenuItem_Click(object sender, EventArgs e)
{
// Get the reference to the Singleton, NOTE that you do not create an instance
// of Form3 but by using the Form3 Instance property it will create it if needed
thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Get the reference to the Singleton
secondForm = Form2.Instance;
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout;
frmAbout = new AboutBox1();
frmAbout.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
// Get the reference to the Singleton
fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
// Get the reference to the Singleton
thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
}
}
}
Hi Smanyx;
One small error in my last post, lines like this one
thirdForm = Form3.Instance;
need a type of the form being created because I removed the class levels declares. For example
Form3 thirdForm = Form3.Instance;
Fernando
One small error in my last post, lines like this one
thirdForm = Form3.Instance;
need a type of the form being created because I removed the class levels declares. For example
Form3 thirdForm = Form3.Instance;
Fernando
Did that help?
ASKER
>>>Did that help?
Sorry, FernandoSoto:, I did not have the chance to implement that yet. I am posting something as soon as I try it on.
Please, bear with me...
Sorry, FernandoSoto:, I did not have the chance to implement that yet. I am posting something as soon as I try it on.
Please, bear with me...
ASKER
I tried to implement the suggested changes. I am getting quite a few errors.
Let me explain my app first, so you could guide me better.
I have 4 Forms: Form1 is just a Login Form
Form2 is Students Management
Form3 is Classes Management
Form4 is Teachers Management
I have tried to make the changes to all the Forms codes.
These are the error messages I get:
Error 1 Cannot implicitly convert type 'windowsapp.Form1' to 'windowsapp.Form2' I:\CS_SchoolProject\Form4. cs 38 32 windowsapp
Error 2 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form4. cs 46 38 windowsapp
Error 3 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form4. cs 54 37 windowsapp
Error 4 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form3. cs 53 37 windowsapp
Error 5 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form3. cs 61 38 windowsapp
Error 6 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2. cs 64 36 windowsapp
Error 7 Cannot implicitly convert type 'windowsapp.Form1' to 'windowsapp.Form2' I:\CS_SchoolProject\Form2. cs 77 32 windowsapp
Error 8 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2. cs 92 38 windowsapp
Error 9 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2. cs 105 37 windowsapp
Let me explain my app first, so you could guide me better.
I have 4 Forms: Form1 is just a Login Form
Form2 is Students Management
Form3 is Classes Management
Form4 is Teachers Management
I have tried to make the changes to all the Forms codes.
These are the error messages I get:
Error 1 Cannot implicitly convert type 'windowsapp.Form1' to 'windowsapp.Form2' I:\CS_SchoolProject\Form4.
Error 2 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form4.
Error 3 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form4.
Error 4 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form3.
Error 5 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form3.
Error 6 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2.
Error 7 Cannot implicitly convert type 'windowsapp.Form1' to 'windowsapp.Form2' I:\CS_SchoolProject\Form2.
Error 8 'windowsapp.Form4' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2.
Error 9 'windowsapp.Form3' does not contain a definition for 'Instance' I:\CS_SchoolProject\Form2.
FORM2 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public sealed partial class Form2 : Form
{
private static readonly Form1 instance = new Form1();
////declaring a variable secondForm of type Form2
//declaring form variables
public Form2()
{
InitializeComponent();
}
public static Form1 Instance
{
get { return instance;}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void classToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void Form2_Resize(object sender, EventArgs e)
{
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 secondForm = Form2.Instance;
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout;
frmAbout = new AboutBox1();
frmAbout.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void classesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
}
}
}
FORM3 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public sealed partial class Form3 : Form
{
private readonly Form1 instance = new Form1();
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void studentToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void toolStripMenuItem21_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem36_Click(object sender, EventArgs e)
{
}
private void teachersToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem19_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void toolStripMenuItem18_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
}
}
FORM4 CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public sealed partial class Form4 : Form
{
private static readonly Form1 instance = new Form1();
public Form4()
{
InitializeComponent();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void button6_Click(object sender, EventArgs e)
{
// = "Are you sure you want to delete ";
//MessageBox();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 secondForm = Form2.Instance;
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
}
}
Problem & Solution: Allow only one instance of any MDI child form in your MDI application
http://weblogs.asp.net/rosherove/archive/2004/06/16/156933.aspx
http://weblogs.asp.net/rosherove/archive/2004/06/16/156933.aspx
Hi Smanyx;
The Singleton Pattern needs to be implemented on all the classes that you want only one instance of and its constructor must be a private NOT public. Please see comments in the corrected code.
Fernando
The Singleton Pattern needs to be implemented on all the classes that you want only one instance of and its constructor must be a private NOT public. Please see comments in the corrected code.
Fernando
// Form2 : As a Singleton Pattern
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public sealed partial class Form2 : Form
{
// ===================================================
// This needs to be a private static readonly variable
// ===================================================
private static readonly Form2 instance = new Form2();
// ============================================================
// The pattern states that the constructor needs to be private
// ============================================================
private Form2()
{
InitializeComponent();
}
// ==================================================================================
// You need to implement a property to return a reference to a instance of the class
// ==================================================================================
public static Form2 Instance
{
get { return instance;}
}
// =====================================================================================
// You need to implement the Form Closing event so that the form does not get disposed
// =====================================================================================
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void classToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void Form2_Resize(object sender, EventArgs e)
{
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 secondForm = Form2.Instance;
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAbout;
frmAbout = new AboutBox1();
frmAbout.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void classesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
}
}
}
// Form3 : As a Singleton Pattern
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public sealed partial class Form3 : Form
{
// ===================================================
// This needs to be a private static readonly variable
// ===================================================
private static readonly Form3 instance = new Form3();
// ============================================================
// The pattern states that the constructor needs to be private
// ============================================================
private Form3()
{
InitializeComponent();
}
// ==================================================================================
// You need to implement a property to return a reference to a instance of the class
// ==================================================================================
public static Form3 Instance
{
get { return instance; }
}
// =====================================================================================
// You need to implement the Form Closing event so that the form does not get disposed
// =====================================================================================
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void studentToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void toolStripMenuItem21_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem36_Click(object sender, EventArgs e)
{
}
private void teachersToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
private void toolStripMenuItem19_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
private void toolStripMenuItem18_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
}
}
// Form4 : As a Singleton Pattern
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public sealed partial class Form4 : Form
{
// ===================================================
// This needs to be a private static readonly variable
// ===================================================
private static readonly Form4 instance = new Form4();
// ============================================================
// The pattern states that the constructor needs to be private
// ============================================================
private Form4()
{
InitializeComponent();
}
// ==================================================================================
// You need to implement a property to return a reference to a instance of the class
// ==================================================================================
public static Form4 Instance
{
get { return instance; }
}
// =====================================================================================
// You need to implement the Form Closing event so that the form does not get disposed
// =====================================================================================
private void Form4_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void button6_Click(object sender, EventArgs e)
{
// = "Are you sure you want to delete ";
//MessageBox();
}
private void helpToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void manageStudentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 secondForm = Form2.Instance;
//thirdForm.Size = new Size(524, 368);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
private void manageTeachersToolStripMenuItem_Click(object sender, EventArgs e)
{
Form4 fourthForm = Form4.Instance;
//thirdForm.Size = new Size(524, 368);
fourthForm.StartPosition = FormStartPosition.CenterScreen;
fourthForm.Show();
}
private void manageClassesToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterScreen;
thirdForm.Show();
}
}
}
ASKER
Hi Fernando;
I tried to carefully implement all the changes you suggested. But, I am getting an error message:
Error 1 An object reference is required for the non-static field, method, or property 'windowsapp.Form3.instance ' I:\CS_SchoolProject\Form3. cs 22 26 windowsapp
this error is pointing to
public static Form3 Instance
{
get { return instance; }
}
If I change from instance to Instance, the program runs but then gives me a "StackOverflowException" still pointing at that same
public static Form3 Instance
{
get { return instance; }
}
What could the problem be?
Also, I am submitting the code for Form1, I have made a little change in calling Form2 to display essentially. Please do check at let me know.
Thanks.
I tried to carefully implement all the changes you suggested. But, I am getting an error message:
Error 1 An object reference is required for the non-static field, method, or property 'windowsapp.Form3.instance
this error is pointing to
public static Form3 Instance
{
get { return instance; }
}
If I change from instance to Instance, the program runs but then gives me a "StackOverflowException" still pointing at that same
public static Form3 Instance
{
get { return instance; }
}
What could the problem be?
Also, I am submitting the code for Form1, I have made a little change in calling Form2 to display essentially. Please do check at let me know.
Thanks.
FORM1 CODE:
===========
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox3.Text == "admin" && textBox4.Text == "password")
{
MessageBox.Show("Welcome to the System!");
//declaring a variable secondForm of type Form2
Form2 secondForm = Form2.Instance;
//secondForm = new Form2();
secondForm.Size = new Size(500, 534);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
else
MessageBox.Show("Wrong Password, Please Try Again...");
}
private void textBox4_Enter(object sender, EventArgs e)
{
//button2.Enabled = true;
//button2.Focus();
}
private void textBox3_Enter(object sender, EventArgs e)
{
//textBox4.Focus();
}
}
}
At the top of Fernando's example, he has a private member to hold the instance.
It's line #18 in his post here:
https://www.experts-exchange.com/questions/25662204/Windows-Forms-One-instance-not-multiple-instances-of-a-Form.html#29913886
So in Form3, you need to add inside the class:
private static readonly Form3 instance = new Form3();
A similar line with the correct Form type should be inside each form that you need to be a singleton.
I have another similar example here that you can model from:
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
It's line #18 in his post here:
https://www.experts-exchange.com/questions/25662204/Windows-Forms-One-instance-not-multiple-instances-of-a-Form.html#29913886
So in Form3, you need to add inside the class:
private static readonly Form3 instance = new Form3();
A similar line with the correct Form type should be inside each form that you need to be a singleton.
I have another similar example here that you can model from:
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
ASKER
Thank you guys, but there still is a little problem. Navigating between Forms is not 'smooth' I mean, once there's been an open instance of a FormX, if I click on the menu to run for example this code:
private void toolStripMenuItem19_Click( object sender, EventArgs e)
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterSc reen;
thirdForm.Show();
}
The selected Form (Form3 in this case), should come, selected, over the other forms, right?! Or should add additional code for that to happen?
The Form is available in the Task bar but I want it to pop up on the screen on top of the other windows.
Also, the application doesn't close anymore when I click the Exit button. If I don't click on the menus to have different instances of the Forms, the application does close correctly. What could the problem be?
Here is the code for existing the app. The closing messages will show up but the application won't close.
private void button3_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Bu tton2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void toolStripMenuItem19_Click(
{
Form3 thirdForm = Form3.Instance;
//thirdForm.Size = new Size(524, 368);
thirdForm.StartPosition = FormStartPosition.CenterSc
thirdForm.Show();
}
The selected Form (Form3 in this case), should come, selected, over the other forms, right?! Or should add additional code for that to happen?
The Form is available in the Task bar but I want it to pop up on the screen on top of the other windows.
Also, the application doesn't close anymore when I click the Exit button. If I don't click on the menus to have different instances of the Forms, the application does close correctly. What could the problem be?
Here is the code for existing the app. The closing messages will show up but the application won't close.
private void button3_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Bu
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
Adding this should bring the form to front
thirdForm.Activate();
thirdForm.Activate();
ASKER
>>>thirdForm.Activate();
This works. But if the user minimises the Form, then clicking on the menu doesn't bring the Form back on, selected. How can I also cater from this case?
Also, why is it that the application doesn't close after I tempered with the Forms??
If I run the program and do nothing with the forms, the application closes just fine. But, if I load the different Forms then then close them before exiting, the app doesn't close. What's wrong?
Thanks.
This works. But if the user minimises the Form, then clicking on the menu doesn't bring the Form back on, selected. How can I also cater from this case?
Also, why is it that the application doesn't close after I tempered with the Forms??
If I run the program and do nothing with the forms, the application closes just fine. But, if I load the different Forms then then close them before exiting, the app doesn't close. What's wrong?
Thanks.
On the Application tab of project properties, make sure the ShutDown mode is "When startup form closes"
Screen.jpg
Screen.jpg
ASKER
My application tab is a bit different. How do I go here?
screen.docx
screen.docx
Is it visual studio 2008? Is it a Windows Application project template?
ASKER
I am using Microsoft Visual C# 2008 Express Edition.
I have created the entire project from scratch, I haven't used project template.
I have created the entire project from scratch, I haven't used project template.
Can you post the form that when you start the program it is displayed.
ASKER
Hi Fernando,
Here is the code for the login screen and screen print if it's going to help...
Students Management is Form2.
Thanks.
screen3.doc
Here is the code for the login screen and screen print if it's going to help...
Students Management is Form2.
Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace windowsapp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
string message = "Are You Sure You Want To Quit?"; // Message
string caption = "Quitting Application..."; // Caption
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
//MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button2;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes)
{
string message2 = "Do You Want To Save Changes?"; // Message
string caption2 = "Saving Changes..."; // Caption
MessageBoxButtons buttons2 = MessageBoxButtons.YesNo;
DialogResult result2;
result2 = MessageBox.Show(message2, caption2, buttons2);
if (result2 == DialogResult.Yes)
{
//saving code goes here
}
Application.Exit();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox3.Text == "admin" && textBox4.Text == "password")
{
MessageBox.Show("Welcome to the System!");
//declaring a variable secondForm of type Form2
Form2 secondForm = Form2.Instance;
//secondForm = new Form2();
secondForm.Size = new Size(500, 534);
secondForm.StartPosition = FormStartPosition.CenterScreen;
secondForm.Show();
}
else
MessageBox.Show("Wrong Password, Please Try Again...");
textBox4.Text = "";
textBox4.Focus();
}
private void textBox4_Enter(object sender, EventArgs e)
{
//button2.Enabled = true;
//button2.Focus();
}
private void textBox3_Enter(object sender, EventArgs e)
{
//textBox4.Focus();
}
}
}
screen2.docscreen3.doc
Hi Smanyx;
To your question, "If I run the program and do nothing with the forms, the application closes just fine. But, if I load the different Forms then then close them before exiting, the app doesn't close. What's wrong?", Looking at your main form, Form1, it should close fine unless some project options are set to close after all other forms have been closed and the way it is set up now that will not happen because the other forms are never closed but just hidden. Not having VS 2008 Express Edition I would not be able to tell where to look.
If you can zip your project and then change the extension to txt and then zip that file and load it up to this site I will have a look at it.
Fernando
To your question, "If I run the program and do nothing with the forms, the application closes just fine. But, if I load the different Forms then then close them before exiting, the app doesn't close. What's wrong?", Looking at your main form, Form1, it should close fine unless some project options are set to close after all other forms have been closed and the way it is set up now that will not happen because the other forms are never closed but just hidden. Not having VS 2008 Express Edition I would not be able to tell where to look.
If you can zip your project and then change the extension to txt and then zip that file and load it up to this site I will have a look at it.
Fernando
>because the other forms are never closed but just hidden.
Is that a good idea by the way?
In one of my projects, I use this property in a module
Public ReadOnly Property GetAdapter() As SqlDataAdapter
Get
If IsNothing(_dbadp) Then
_dbadp = New SqlDataAdapter("", My.Settings.ConnectionStri ng)
ElseIf IsNothing(_dbadp.SelectCom mand) Then
_dbadp = New SqlDataAdapter("", My.Settings.ConnectionStri ng)
End If
_dbadp.SelectCommand.Param eters.Clea r()
Return _dbadp
End Get
End Property
I think rather than overriding the FormClosing and just hiding the form, the form should be disposed instead. When an instance is required, it should return the existing instance if one exists or create a new one otherwise.
Is that a good idea by the way?
In one of my projects, I use this property in a module
Public ReadOnly Property GetAdapter() As SqlDataAdapter
Get
If IsNothing(_dbadp) Then
_dbadp = New SqlDataAdapter("", My.Settings.ConnectionStri
ElseIf IsNothing(_dbadp.SelectCom
_dbadp = New SqlDataAdapter("", My.Settings.ConnectionStri
End If
_dbadp.SelectCommand.Param
Return _dbadp
End Get
End Property
I think rather than overriding the FormClosing and just hiding the form, the form should be disposed instead. When an instance is required, it should return the existing instance if one exists or create a new one otherwise.
@CodeCruiser...that's they way I tend to do it as well:
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
https://www.experts-exchange.com/questions/21811534/Window's-form.html#16453671
@Idle_Mind
I think that is an efficient way especially when Forms are involved.
I think that is an efficient way especially when Forms are involved.
ASKER
Unfortunately, I am unable to upload the project. I tried to zip it, change the file extension to txt. Then I can't re-zip it. When I attach it, the system does not allow it to be uploaded. Giving this error message:
The extension of one or more files in the archive is not in the list of allowed extensions: CS_SchoolProjectII/obj/Deb ug/windows app.AboutB ox1.resour ces What a shame!
I have had a closer look at both codes suggested by Idle_Mind and CodeCruiser. But I am finding it hard to adapt them to my project. I reckon, they might be able to achieve what I want, but I' m still in a learning curve with very little experience. So, could you please guide me so that I can take advantage of these codes, implement them to my project to try it out. That way I'll also understand them better because they would apply to something I am building.
Thank you!
The extension of one or more files in the archive is not in the list of allowed extensions: CS_SchoolProjectII/obj/Deb
I have had a closer look at both codes suggested by Idle_Mind and CodeCruiser. But I am finding it hard to adapt them to my project. I reckon, they might be able to achieve what I want, but I' m still in a learning curve with very little experience. So, could you please guide me so that I can take advantage of these codes, implement them to my project to try it out. That way I'll also understand them better because they would apply to something I am building.
Thank you!
Hi Smanyx;
Experts-Exchange has an old web site to upload and download files from question it still seems to work. Go to this link, http://www.ee-stuff.com/login.php , the username and password is the same that you use on this site. Once you are logged in click on the tab at the top of the page called "Expert Area". On this page locate "File Upload/Storage" and click on "Upload a new file" then follow the instruction. Once the file is uploaded it will return to you two links please post them here. Before starting this process zip the project files as normal so that it can be uploaded.
Fernando
Experts-Exchange has an old web site to upload and download files from question it still seems to work. Go to this link, http://www.ee-stuff.com/login.php , the username and password is the same that you use on this site. Once you are logged in click on the tab at the top of the page called "Expert Area". On this page locate "File Upload/Storage" and click on "Upload a new file" then follow the instruction. Once the file is uploaded it will return to you two links please post them here. Before starting this process zip the project files as normal so that it can be uploaded.
Fernando
ASKER
Hi Fernando,
Here are the two links:
Your file has successfully been uploaded!
To download the file, you must be logged into EE-Stuff. Here are two pages that will display your file, if logged in:
View all files for Question ID: 25662204
https://filedb.experts-exchange.com/incoming/ee-stuff/7882-CS_SchoolProject.zip
Direct link to your file
https://filedb.experts-exchange.com/incoming/ee-stuff/7882-CS_SchoolProject.zip
Thanks.
Here are the two links:
Your file has successfully been uploaded!
To download the file, you must be logged into EE-Stuff. Here are two pages that will display your file, if logged in:
View all files for Question ID: 25662204
https://filedb.experts-exchange.com/incoming/ee-stuff/7882-CS_SchoolProject.zip
Direct link to your file
https://filedb.experts-exchange.com/incoming/ee-stuff/7882-CS_SchoolProject.zip
Thanks.
ASKER
Login details;
userame: admin
password: password
userame: admin
password: password
Hi Smanyx;
This will correct the issues.
For the FormClosing events for Form2, Form3 and Form4 add code from this
this.Hide();
e.Cancel = true;
To look like this.
if (e.CloseReason != CloseReason.ApplicationExi tCall)
{
this.Hide();
e.Cancel = true;
}
Also make sure that Form2 FormClosing is wired up because on the project you uploaded it was not.
Fernando
This will correct the issues.
For the FormClosing events for Form2, Form3 and Form4 add code from this
this.Hide();
e.Cancel = true;
To look like this.
if (e.CloseReason != CloseReason.ApplicationExi
{
this.Hide();
e.Cancel = true;
}
Also make sure that Form2 FormClosing is wired up because on the project you uploaded it was not.
Fernando
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you so much guys.
It's working fine now. I still have a lot to do on this app. Anytime I get stuck, I'll surely call upon you:)
I really appreciated your help and your input.
Smanyx
It's working fine now. I still have a lot to do on this app. Anytime I get stuck, I'll surely call upon you:)
I really appreciated your help and your input.
Smanyx
For Each f As Form in Application.OpenForms
If TypeOf(f) Is frmChildForm Then
'form already open
End If
Next