Problems with Savedialog and Windows Forms output function

Asked

Viewed 27 times

0

Guys, here’s the deal: I’m making a notepad in C# for educational purposes and I come across a mistake I haven’t been able to see for two days. Whenever I will save a txt file it opens the window for me to choose where I want to save the file, so far so good. Only when I hit save, it does not terminate the application, it asks again if I want to save the file.

When I press ALT+F4 (click on exit) it asks if I want to save the file, be it by clicking yes or in nay it back ask the same thing again, only the second time it either saves and closes or simply closes the application. Follow the code:

private void SalvarClick(object sender, EventArgs e)
    {

        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Arquivo texto | *.txt";
        sfd.ShowDialog();

           if(string.IsNullOrEmpty(sfd.FileName) == false)
           {
               try
               {
                   using (StreamWriter writer = new StreamWriter(sfd.FileName, false, Encoding.UTF8))
                   {
                       writer.Write(JanelaDeTxt.Text);
                       writer.Flush();
                      //Application.Exit();
                       this.Close();
                   }
               }
               catch(Exception ex)
               {
                   MessageBox.Show(string.Format("Não foi possível salvar o arquivo. Erro: [0]", ex.Message), "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);                  
               }

           }

    }

exit function

private void sairToolStripMenuItem_Click(object sender, EventArgs e)
    {

        if (!string.IsNullOrEmpty(this.JanelaDeTxt.Text))
        {
            DialogResult result = MessageBox.Show("Deseja salvar arquivo?", "Sair do programa", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {                  
                SalvarClick(sender, e);
            }
            else if(result == DialogResult.No)
            {
                Application.Exit(); 
            }
        }
        else
        {
            Application.Exit();
        }
    }
  • Do a search in the form looking for SalvarClick and then looking for sairToolStripMenuItem_Click and add to the question all the places where these two functions are used.

  • Also that @Pedrogaspar said, there’s a lot of weird stuff and it shouldn’t be like that in this code. I’m talking because you’re using it for teaching purposes and I imagine you’d like to receive this feedback. I won’t say what because there are several things and the question isn’t about that either, but there is the hint that is learning to do something wrong, even if it works (some things maybe are just a matter of outdated style).

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.