2015-08-15 4 views
1

У меня есть приложение C#, у которого есть логин, который использовал пользовательскую таблицу SQL-сервера для аутентификации.Закрытие формы возвращает ошибку

Проблема, с которой я сталкиваюсь: когда я выхожу из приложения, она выдает следующее сообщение об ошибке.

enter image description here

Что будет возможное решение?

Общий код:

private void logIn() 
     { 
      try 
      { 
       if (txtpwd.Text == "" || txtusername.Text == "") 
       { MessageBox.Show("Field is Blank!", "SQL Server", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } 


       int i = 0; // we use this variable to count if ther’s a user with this name 

       conn = new SqlConnection(Scon.ReturnConnection()); 
       SqlCommand cmd = new SqlCommand(); 
       cmd.CommandText = "select * from Users"; 
       cmd.Connection = conn; 
       conn.Open(); 
       //cmd.Parameters.AddWithValue("@type", cmbType.Text); 
       SqlDataReader sdr = cmd.ExecuteReader(); 


       while (sdr.Read()) 
       { 
        string un = sdr["userid"].ToString(); 
        string pd = sdr["pwd"].ToString(); 
        string ut = sdr["usertype"].ToString(); 

        if (un == txtusername.Text) 
        { 
         ++i; 
         if (pd == txtpwd.Text) 
         { 
          Form panel; 
          this.Opacity = 0; 
          switch (ut) 
          { 
           case "admin": 

            panel = new GeneralSetting(); 
            LoginRegister(); 
            panel.Show();         

            break; 
           case "user": 
            panel = new frmStockManagement(); 

             if (fsm == null) 
             { 
              this.Hide();           
              fsm = new frmStockManagement(); //Create form if not created 
              fsm.FormClosed += (s, args) => this.Close(); //Add eventhandler to cleanup after form closes 
              Thread.Sleep(3000); 
             } 
             LoginRegister(); 

             fsm.ShowDialog(this); //Show Form assigning this form as the forms owner 

            break; 
          } 
         } 
         else 
         { 
          MessageBox.Show("Wrong Password!", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error); 
         } 
       } 
       } 
       if (i == 0) 

      MessageBox.Show("No specified user with this name!", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error); 

      } 
      catch (SqlException sEx) 
      { 
       MessageBox.Show(sEx.Message, "Login", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      finally 
      { 
       conn.Close(); 
      } 
     } 

     void fsm_FormClosed(object sender, FormClosedEventArgs e) 
     { 
      // fsh = null; //If form is closed make sure reference is set to null 
      Show(); 
     } 
     private void button2_Click(object sender, EventArgs e) 
     { 
      Application.Exit(); 
     } 
     private bool IsServerConnected() 
     { 

      using (var l_oConnection = new SqlConnection(Scon.ReturnConnection())) 
      { 
       try 
       { 
        l_oConnection.Open(); 
        return true; 
        //MessageBox.Show("Connection Availabel!", "SQL Server", MessageBoxButtons.OK, MessageBoxIcon.Information); 
       } 
       catch (SqlException) 

       { 
        MessageBox.Show("No Connection to the server", "SQL Server", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        GeneralSetting setting = new GeneralSetting(); 
        setting.ShowDialog(); 
        this.Hide(); 
        this.Close();     
        return false; 
       } 
      } 
     } 

ответ

2

У вас есть multy-threading проблемы. Вы должны использовать метод Control.Invoke для взаимодействия с элементами пользовательского интерфейса (формами):

this.Invoke(new Func<DialogResult>(() => fsm.ShowDialog(this))); 
+0

Действительно возможное решение. Могу ли я использовать это для каждого типа многопоточных проблем? –

+0

@NurSelam для winforms многопотоковых проблем – Backs

+0

Хорошо спасибо @Backs –

Смежные вопросы