Home > Net >  How to retain the value from an numericupdown after closing a form
How to retain the value from an numericupdown after closing a form

Time:10-14

I have the following question. I am using C# .NET, and I want to save a value in numericupdown box after I close my form. In my aplication I have in total 2 forms, so I want to save the value I enter in the second one, and after I open it again I want to see the last value. In my case the numericupdown value is empty after I open the second form again.

I was thinking about something like this:

namespace Project2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            decimal a = numericUpDown1.Value;
            label2.Text = "N: "   a;
        }
    }
}

But is still empty after I open it again.

CodePudding user response:

You can use static variable to store last updated value and with the reference of class name you can use it where ever you want.

From MSDN: Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Like,

namespace Project2
{
    public partial class Form2 : Form
    {
        public static decimal lastNumericUpDownValue = 0;  
        public Form2()
        {
            //For example: thiw will print lastest saved Numeric updown value.
            //For the first time, it will print 0
            Console.WriteLine(Form2.lastNumericUpDownValue);
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Assign value to lastNumericUpDownValue variable. Look at how it is used.
            Form2.lastNumericUpDownValue = numericUpDown1.Value;
        }
    }
}

CodePudding user response:

You can create a class which provides set/get for a NumericUpDown control in this case using the following.

public sealed class Setting
{
    private static readonly Lazy<Setting> Lazy = 
        new Lazy<Setting>(() => new Setting());
    public static Setting Instance => Lazy.Value;
    public decimal NumericUpDownValue { get; set; }
}

In the child form, OnShown set Value property to Settings.NumericUpDownValue then OnClosing remember the value.

public partial class ChildForm : Form
{
    public ChildForm()
    {
        InitializeComponent();

        Shown  = (sender, args) => 
            numericUpDown1.DataBindings.Add("Value", Setting.Instance, 
                nameof(Setting.NumericUpDownValue));

        Closing  = (sender, args) => 
            Setting.Instance.NumericUpDownValue = numericUpDown1.Value;
    }
}

The code above, specifically Settings class is known as the Singleton Pattern which you can learn more about in Implementing the Singleton Pattern in C#.

  • Related