【问题标题】:How to retain the value from an numericupdown after closing a form关闭表单后如何保留 numericupdown 中的值
【发布时间】:2021-10-14 08:32:45
【问题描述】:

我有以下问题。我正在使用 C# .NET,我想在关闭表单后在 numericupdown 框中保存一个值。在我的应用程序中,我总共有 2 个表单,所以我想保存我在第二个表单中输入的值,然后再次打开它后,我想查看最后一个值。在我的情况下,再次打开第二个表单后 numericupdown 值为空。

我在想这样的事情:

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;
        }
    }
}

但我再次打开后仍然是空的。

【问题讨论】:

  • 下次打开Form2时要在哪里使用。你能告诉我们那个代码吗?

标签: c# forms save numericupdown


【解决方案1】:

在这种情况下,您可以使用以下方法创建一个为 NumericUpDown 控件提供 set/get 的类。

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; }
}

在子窗体中,OnShown 将 Value 属性设置为 Settings.NumericUpDownValue 然后 OnClosing 记住该值。

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;
    }
}

上面的代码,特别是设置类被称为单例模式,您可以在Implementing the Singleton Pattern in C#中了解更多信息。

【讨论】:

    【解决方案2】:

    您可以使用static variable 来存储上次更新的值,并参考类名,您可以在任何需要的地方使用它。

    From MSDN: 静态字段的两个常见用途是保持计数 已实例化的对象,或存储一个必须 在所有实例之间共享。

    喜欢,

    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;
            }
        }
    }
    

    【讨论】:

    • 请看我的更新评论。
    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2023-03-25
    • 2013-11-03
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    相关资源
    最近更新 更多