Application Exit Collection was modified; enumeration operation may not execute - c#

I am getting this error Collection was modified; enumeration operation may not execute.
I have 3 forms. These are the form closing events of all 3 I did some research and learnt that some from was modified/shown inturn causing this error
Form1
private void btnExitl_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmPlant_FormClosing(object sender, FormClosingEventArgs e)
{
if (DataDirty)
{
if (DialogResult.Yes == MessageBox.Show("Are you sure you want to exit", "Data Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
Application.Exit();
else
e.Cancel = true;
}
else
Application.Exit();
}
Form2:
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmInputFiles_FormClosing(object sender, FormClosingEventArgs e)
{
int plantid = StaticClass.GlobalValue;
//Properties.Settings.Default.PlantId = plantid;
Program.fPlant = new frmPlant(plantid);
Program.fPlant.Show();
e.Cancel = false;
//this.Hide();
}
Form3:
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmVesselData_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result;
int fileId = StaticClass.FileGlobal;
if (DataDirty)
{
string messageBoxText = "You have unsaved data. Do you want to save the changes and exit the form?";
MessageBoxButtons button = MessageBoxButtons.YesNo;
string caption = "Data Changed";
MessageBoxIcon icon = MessageBoxIcon.Question;
result = MessageBox.Show(messageBoxText, caption, button, icon);
if (result == DialogResult.No)
{
Program.fInputFiles = new frmInputFiles(gPlantId, gPlantName);
Program.fInputFiles.Show();
//e.Cancel=true;
}
if (result == DialogResult.Yes)
{
e.Cancel = true;
//return;
}
}
else
{
Program.fInputFiles = new frmInputFiles(gPlantId, gPlantName);
Program.fInputFiles.Show();
//e.Cancel = false;
}
}
It happens only when I view the third form(Form3). Form1, Form2 work well,. But if I view form3 and try to go back to form1
So somewhere in the closing event of form3, form1
My guess is the btnExit_close event of the form this.close()
Thank you

Simply call Environment.Exit(0);

While closing your First Form try this on FormClosingEvent
private void frmPlant_FormClosing(object sender, FormClosingEventArgs e)
{
if (DataDirty)
{
if (DialogResult.Yes == MessageBox.Show("Are you sure you want to exit", "Data Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
this.Close();
Application.Exit();
}
else
e.Cancel = true;
}
else
Application.Exit();
}
Call this.Close() first and then Application.Exit(), Application.Exit() terminates all processes and Close() close your main form

Related

close warning keep poping up

There is two forms in my program,The first one is a simple login form that after everything was right loginform hides and the other shows.
But the problem is if i try to close the program at loginform and press no then when i press signin button with correct values the closing messagebox shows up again with no reason!!!!
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult DR= MessageBox.Show("do you want to exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
if (DR == DialogResult.Yes)
Application.Exit();
else if (DR == DialogResult.No)
e.Cancel=true;
}
}
private void Sign_in_Button_Click(object sender, EventArgs e)
{
if (AccountExistStatus(UserNameLogin.Text)==true&&PasswordMatch(PasswordLogin.Text))
{
this.Hide();
}
else if (UserNameLogin.Text == "Echo" && PasswordLogin.Text == "XLVI")
{
this.Hide();
}
}
I think your problem is that you have just hidden that Login form, you have not closed it anywhere. Have a look at the following code which solves your problem. it will close your LoginForm also at the close of the next form
private void Sign_in_Button_Click(object sender, EventArgs e)
{
if (AccountExistStatus(UserNameLogin.Text)==true&&PasswordMatch(PasswordLogin.Text))
{
DisplayForm2();
}
else if (UserNameLogin.Text == "Echo" && PasswordLogin.Text == "XLVI")
{
DisplayForm2();
}
}
void DisplayForm2() {
this.Hide();
var form2 = new Form2();
form2.Closed += (s, args) => this.Close();
form2.Show();
}

how to exit from application on click of (red X ) button right top on winform

i have two forms in my application. frmLogin and frmDash. after login. i am hiding frmLogin on click of login button. ad showing frmDash.
in frmDash, there is LogOut button. on click of LogOut, i am using this.Close() and showing login form. but now if i click (red X) button of frmLogin whole application is not terminating. plz give some suggestions.
i have tried this.:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
this.Hide();
string Log_API = "http://api.retailbutton.co/WS/Service.php?Service=employeeLogin";
if (LoginUser(Log_API))
{
logIn_Status = "true";
GlolbalUtil.LogIn_Status = logIn_Status;
frmDash frmDash = new frmDash();
frmDash.Owner = this;
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
//GlolbalUtil.accept_status = "1";
}
else
{
MessageBox.Show("Please Check Username and password");
FrmLogin frmLogin = new FrmLogin();
frmLogin.Owner = this;
frmLogin.Show();
}
}
code for Logout button of frmDash:
private void button1_Click(object sender, EventArgs e)
{
GlolbalUtil.LogIn_Status = "false";
this.Close();
FrmLogin fl = new FrmLogin();
fl.Show();
}
You create a new instance of frmDash when you log in and hide the form.
Then when you are logging out, you say this.close() and create another new instance of FrmLogin. Not going back to the original instance of FrmLogin.
This means that you will always will have the hidden instance which you started with.
(If you close the new instance of FrmLogin, the hidden FrmLogin still exists.)
You can add the following in btnLogin_Click:
frmDash.ParentForm = this;
and button1_Click should look like this:
private void button1_Click(object sender, EventArgs e){
GlolbalUtil.LogIn_Status = "false";
FrmLogin fl = (FrmLogin)this.Parent; //Prior it said ParentForm
this.Close();
fl.Show();
}
If you implement this, you will show the initial login form and when you close it, you close the initial instance of the login form.
#Edit 10:52 25-06-2015
ParentForm cannot be assigned and is read only. A solution is to assign it to Parent or the following can also be applied in btnLogin_Click:
frmDash.Owner = this;
and button1_Click:
private void button1_Click(object sender, EventArgs e){
GlolbalUtil.LogIn_Status = "false";
FrmLogin fl = (FrmLogin)this.Owner
this.Close();
fl.Show();
}
#Edit 08:16 29-06-2015 (Next question)
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string Log_API = "http://api.retailbutton.co/WS/Service.php?Service=employeeLogin";
if (LoginUser(Log_API))
{
logIn_Status = "true";
GlolbalUtil.LogIn_Status = logIn_Status;
frmDash frmDash = new frmDash();
frmDash.Owner = this;
////If you hide here, you do not have to make
//a new instance when the if statement is not true.////
this.Hide();
frmDash.Show();
txtUsername.Text = "";
txtPassword.Text = "";
//GlolbalUtil.accept_status = "1";
}
else
{
MessageBox.Show("Please Check Username and password");
////Delete following////
//FrmLogin frmLogin = new FrmLogin();
//frmLogin.Owner = this;
//frmLogin.Show();
}
}
If you are using a custom button, do this
private void QuitButton_Click(object sender, EventArgs e)
{
DialogResult DialogResult = MessageBox.Show("Do you really want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (DialogResult == DialogResult.Yes)
Application.Exit();//Here is the code to close everything
else
//Do stuff
}
If you are using the X button, add a FormClosing Event and the code look like this:
private void Form1_FormClosing(object sender, FormClosingEventArgs e){
DialogResult DialogResult = MessageBox.Show("Do you really want to exit?", "Confirmation",
MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (DialogResult == DialogResult.Yes)
Application.Exit();//Here is the code to close everything
else
//Do stuff
}
use Application.Exit(); method when your button clicked
Add this to your Designer.cs
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.SampleClassName_FormClosed);
then right click the SampleClassName_FormClosed and click "Go to Definition".
then inside the created class call the form that you want to close.
Try the following on your 2. Form:
public partial class Form2 : Form
{
private bool ForceClose = true;
public Form2()
{
InitializeComponent();
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (ForceClose)
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
GlolbalUtil.LogIn_Status = "false";
ForceClose = false;
this.Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();//close the whole program using x (red)button
}

Terminate an application with ContextMenuStrip

I want to hide my application in system tray when I click the Form Closing button(clasic red X button). I provided with this code;
private void Ana_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
So, the application is stil running in the system tray. I have added a ContextMenuStrip and when I right click on mouse ContextMenuStrip a Close button comes up but when I click that Close button the application is still running.
I want to terminate the application when I click that Close button. Here is my code:
private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
{
DialogResult ext;
ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ext == DialogResult.Yes)
{
Application.Exit();
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
}
Calling Application.Exit() will actually attempt to close all your forms, and because your FormClosing is hard coded to be cancelled, then it cannot complete the task.
One option with your current structure would be to create an AllowClose flag. This could be a property of the Form, or it could be a global static value.
For example:
//in your form
public bool AllowClose {get;set;}
private void Ana_FormClosing(object sender, FormClosingEventArgs e)
{
if(!AllowClose)
{
e.Cancel = true;
this.Hide();
}
}
//in your context menu event
private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
{
DialogResult ext;
ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ext == DialogResult.Yes)
{
this.AllowClose = true;
Application.Exit();
}
}
Try this,
bool isClosing = false;
private void Ana_FormClosing(object sender, FormClosingEventArgs e)
{
if(!isClosing)
{
e.Cancel = true;
this.Hide();
}
}
private void kapatToolStripMenuItem_Click(object sender, EventArgs e) //Close
{
DialogResult ext;
isClosing = true;
ext = MessageBox.Show("Çıkmak İstediğinizden Emin misiniz?", "Onay", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ext == DialogResult.Yes)
{
Application.Exit();
}
}

C# Minimize to system tray on close

Hi In my c# application I am trying to minimize application to systems tray, when the form is closed. Here is the code I have tried.
public void MinimizeToTray()
{
try
{
notifyIcon1.BalloonTipTitle = "Sample text";
notifyIcon1.BalloonTipText = "Form is minimized";
if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and I am calling the method to form closing event. But the problem is its not minimizing to tray. Its just closing the form.
e.Cancel = true; code will be always cancelling the event even if you shut the computer down, but here is a code that helps you:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
myNotifyIcon.Visible = true;
this.Hide();
e.Cancel = true;
}
}
It will allow closing the form programmaticaly.
Write a event in Form Closing event.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
And write using Custom menu strip for notification icon for to show.
namespace MinimizeTrayNotification
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void MinimzedTray()
{
notifyIcon1.Visible = true;
notifyIcon1.Icon = SystemIcons.Application;
notifyIcon1.BalloonTipText = "Minimized";
notifyIcon1.BalloonTipTitle = "Your Application is Running in BackGround";
notifyIcon1.ShowBalloonTip(500);
}
private void MaxmizedFromTray()
{
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipText = "Maximized";
notifyIcon1.BalloonTipTitle = "Application is Running in Foreground";
notifyIcon1.ShowBalloonTip(500);
}
private void Form1_Resize(object sender, EventArgs e)
{
if(FormWindowState.Minimized==this.WindowState)
{
MinimzedTray();
}
else if (FormWindowState.Normal == this.WindowState)
{
MaxmizedFromTray();
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
Form1 frm = new Form1();
frm.Show();
MaxmizedFromTray();
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
this.Hide();
}
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
notifyIcon1.BalloonTipText = "Normal";
notifyIcon1.ShowBalloonTip(500);
}
}
}
You should cancel the FormClosing event and then call your MinimizeToTray() function.
This is done through the Cancel property of the FormClosingEventArgs.
Also, consider using a bool somewhere to allow closing the Form in some conditions, such as if you're using a File > Exit menu or something:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(!allowClosing)
{
e.Cancel = true;
MinimizeToTray();
}
}
To minimize when closing set WindowState to Minimized
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
e.Cancel = true;
WindowState = FormWindowState.Minimized;
}
You need to use the FormClosing-Event.
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
e.Cancel = true;
MinimizeToTray();
}
You can handle FormClosing Event such as micsoft Form Closing Event as Following example of C#
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if (MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}

C# form X close and btnclose to function the same

How do I make the same functionality for form X (on the top extreme right) and close button. These 2 need to behave alike
This is what I have in btnClose_Click
private void btnClose_Click(object sender, EventArgs e)
{
DialogResult result;
int fileId = StaticClass.FileGlobal;
if (DataDirty)
{
string messageBoxText = "You have unsaved data. Do you want to save the changes and exit the form?";
MessageBoxButtons button = MessageBoxButtons.YesNo;
string caption = "Data Changed";
MessageBoxIcon icon = MessageBoxIcon.Question;
result = MessageBox.Show(messageBoxText, caption, button, icon);
if (result == DialogResult.No)
{
Program.fInput = new frmInputFiles(gtId, gName);
Program.fInput.Show();
this.Close();
}
if (result == DialogResult.Yes)
{
return;
}
}
else
{
Program.fInput = new frmInputFiles(gPlantId, gPlantName);
Program.fInput.Show();
this.Close();
}
}
Even on clicking the X to close the form,it should behave the same way as btnClose_Click
private void frmData_FormClosing(object sender, FormClosingEventArgs e)
{
btnClose_Click(sender,e);//this doesnt seem to be working.
}
It is going in a infinite loop. I understand y it is doing that.. btnClose_Click() has this.Close() which calls frmData_FormClosing.. which inturn calls btnclose..
Thank u
Just put this.Close() in the btnClose_Click() event. Then move all the rest of your logic (you'll need to edit it some) into the frmData_FormClosing() event and call e.Cancel = true; if you want to cancel closing the form (in your case, if there are unsaved changes and the user clicks Yes on the prompt.
Here's an example (I just cut and pasted in notepad, so fair warning):
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void frmData_FormClosing(object sender, FormClosingEventArgs e)
{
if (DataDirty)
{
if (MessageBox.Show("You have unsaved data. Do you want to save the changes and exit the form?",
"Data Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
Program.fInput = new frmInputFiles(gtId, gName);
Program.fInput.Show();
}
else
e.Cancel = true;
}
else
{
Program.fInput = new frmInputFiles(gPlantId, gPlantName);
Program.fInput.Show();
}
}

Categories

Resources