سؤال

In WindowsForms I have an independent class Indicators.cs and a form Food. In the class I have a variable, which I'm changing in the form.

When I open the form, changing the variable, close the form and open it again (without closing the program), then the value of the variable is old. Why so?

Form:

namespace WF
{
    public partial class Computer : Form
    {
        Indicators indicators = new Indicators();

        public Computer()
        {
            if (indicators.isComputerAlreadyRunning == false)
                indicators.isComputerAlreadyRunning = true;
        }
    }
}

Indicators.cs

namespace WF
{
    class Indicators
    {
        public Indicators()
        {

            this.isComputerAlreadyRunning = false;            
        }

        public bool isComputerAlreadyRunning;
    }
}
هل كانت مفيدة؟

المحلول

Create a method in the form class that shows the form and returns a result. This is similar to the MessageBox.Show method. In the example below the FoodForm has a method called ShowForm. This method returns a custom class called FoodFormResult that has all the results needed from the form after it closes.

public FoodFormResult ShowForm()
    {
        return new FoodFormResult(
            ShowDialog() == DialogResult.OK, 
            _indicators);
    }

Every time the form class is created (ex. new FoodForm()), all the existing values in the form are lost.

نصائح أخرى

Many ways to do this..You can create a delegate, save to form's resources, save to external file, save to settings/Appconfig file..So on..

And another but not much recommended for security reasons option is that : You can Create an internal or public static variable in main method of the application..Then when you need set to this variable..

And when you need to call that variable :

//Your main method example
static class Program 
{
   internal static bool AreYouOKAY = false;
   // or public static bool as your needs

   static void Main ()
   { 
       ........
   }

/// And in your form

Program.AreYouOKAY = true;

// After your form closed.. from another form just call as above

if(Program.AreYouOKAY)
{
  MessageBox.Show (" Yeah! I'm Ok!");
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top