-1

I have two winforms. frmMainMenu and frmLogin . In the frmMainMenu I have a menuStrip. Where I have kept some menu including logout option in one of them. So when I login , frmMainMenu comes to the front. I am just not doing anything, Just clicking on logout option frmMainMenu get closed and frmLogin form again shows up. So when click on red cross button of frmLogin form I get the exception error like below:

Unhandled exception has occourred in your application. If you click Continue, the applicaion will ignore this error and attempt to continue. If you click Quit, the application will close immediately.

Collection was modified; enumeration operation may not execute.

Code of frmMainMenu:

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;
using System.Data.SqlClient;
namespace Restaurant_Management_System
{
   public partial class frmMainMenu : Form
  {
    public frmMainMenu()
    {
        InitializeComponent();
    }

    ConnectionString cs = new ConnectionString();

    private void productToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmProduct frm = new frmProduct();
        frm.Show();
    }

    private void categoryToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmCategory frm = new frmCategory();
        frm.Show();
    }

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmAbout frm = new frmAbout();
        frm.Show();
    }


    private void timer1_Tick(object sender, EventArgs e)
    {
        ToolStripStatusLabel4.Text = System.DateTime.Now.ToString();
    }

    private void registrationToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmRegistration frm = new frmRegistration();
        frm.Show();
    }

    private void loginDetailsToolStripMenuItem_Click(object sender, EventArgs e)
    {

           // frmLoginDetails frm = new frmLoginDetails();
        frmPassVerify frm = new frmPassVerify();
        frm.Show();
    }

    private void profileEntryToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmCustomers frm = new frmCustomers();
        frm.Show();
    }

    private void billingToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmSales frm = new frmSales();
        frm.Show();
    }

    private void customersToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmPassVerCus frm = new frmPassVerCus();
        frm.Show();
    }

    private void salesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //frmSalesRecord1 frm = new frmSalesRecord1();
        frmPassVerSale frm = new frmPassVerSale();
        frm.Show();
    }

    private void typeToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmTypeReg frm = new frmTypeReg();
        frm.Show();
    }

    private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
    {
        frmInventory frm = new frmInventory();
        frm.Show();
    }

    //I think here is the problem arises. on clicking the logout

    private void logoutToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        frmLogin frm = new frmLogin();
        this.Dispose();
        frm.Show();

    }
  }
}

code for frmLogin:

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; 
using System.Data.SqlClient; 
namespace Restaurant_Management_System 
{
    public partial class frmLogin : Form
    {
        ConnectionString cs = new ConnectionString();
        DataTable dt = new DataTable();
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == "")
            {
                MessageBox.Show("Please enter user name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserName.Focus();
                return;
            }
            if (txtPassword.Text == "")
            {
                MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }
            try
            {
                SqlConnection myConnection = default(SqlConnection);
                myConnection = new SqlConnection(cs.DBConn);

                SqlCommand myCommand = default(SqlCommand);

                myCommand = new SqlCommand("SELECT Username,password FROM Registration WHERE Username = @username AND password = @UserPassword", myConnection);
                SqlParameter uName = new SqlParameter("@username", SqlDbType.VarChar);
                SqlParameter uPassword = new SqlParameter("@UserPassword", SqlDbType.VarChar);
                //if(txtUserName.Text != "admin")
                uName.Value = txtUserName.Text;
                uPassword.Value = txtPassword.Text;
                myCommand.Parameters.Add(uName);
                myCommand.Parameters.Add(uPassword);

                myCommand.Connection.Open();

                SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                if (myReader.Read() == true)
                {
                    int i;
                    ProgressBar1.Visible = true;
                    ProgressBar1.Maximum = 5000;
                    ProgressBar1.Minimum = 0;
                    ProgressBar1.Value = 4;
                    ProgressBar1.Step = 1;

                    for (i = 0; i <= 5000; i++)
                    {
                        ProgressBar1.PerformStep();
                    }

                        this.Hide();
                        if (txtUserName.Text == "admin")
                        {
                            frmMainMenu frm = new frmMainMenu();
                            frm.Show();
                            frm.lblUser.Text = txtUserName.Text;
                        }
                        if (txtUserName.Text != "admin")
                        {
                            frmMainMenu1 frm = new frmMainMenu1();
                            frm.Show();
                            frm.lblUser.Text = txtUserName.Text;
                        }


                    }


                else
                {
                    MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    txtUserName.Clear();
                    txtPassword.Clear();
                    txtUserName.Focus();

                }
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Dispose();
                }



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ProgressBar1.Visible = false;
            txtUserName.Focus();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
            Application.Exit();

        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Hide();
            frmChangePassword frm = new frmChangePassword();
            frm.Show();
            frm.txtUserName.Text = "";
            frm.txtNewPassword.Text = "";
            frm.txtOldPassword.Text = "";
            frm.txtConfirmPassword.Text = "";
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Hide();
            frmRecoveryPassword frm = new frmRecoveryPassword();
            frm.txtEmail.Focus();
            frm.Show();
        }

     } 
 }

How can I handle this exception ? I dont wanna see this error on closing. thanks in advance :)

Nazmul
  • 500
  • 6
  • 17
  • 5
    Have you seen the countless duplicates with the same error message? Here's the first: http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute Show the stacktrace, where is the exception thrown? – Tim Schmelter Sep 07 '15 at 12:39
  • No. In between two forms only one exception is there – Nazmul Sep 07 '15 at 12:44
  • 1
    Try remove code from _closing event. No need for this. – M_Idrees Sep 07 '15 at 13:09
  • Seems like code is edited and doesn't contain the error part. Can you add exception.ToString() ? – Timur Mannapov Sep 07 '15 at 13:27
  • Why are you Disposing your forms right before exiting the application? What is our application's main form? the main form or the login form? If our mainForm is the application's main form then please remove the Dispose() call within the logoutToolStripMenuItem1_Click, call ShowModal instead of Show on the frmLogin. On the Loginform's btnCancel_Click call DialogResult = DialogResult.Cancel instead of Dispose it. Do the same for Form1_FormClosing (or hide the close icon completely for the login form). call DialogResult = DialogResult.Ok for the OK_Button. Evaluate the result value of ShowModal. – Toni Wenzel Sep 07 '15 at 13:29

1 Answers1

0

Assuming that below event is attached to LogOut Button. Remove/comment this.Dispose(); line

private void logoutToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        frmLogin frm = new frmLogin();
        this.Dispose(); //Comment This Line
        frm.Show();

    }
Abdul Rehman Sayed
  • 6,532
  • 7
  • 45
  • 74