You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# .NET如何在关闭窗体后保留NumericUpDown控件的输入数值

问题根因

每次打开Form2时都会创建全新的窗体实例,控件状态会默认重置为初始值,现有代码没有实现数值的跨实例存储或持久化逻辑,因此重新打开窗体后数值会丢失。

解决方案

方案1:静态变量临时存储(程序运行期间有效,重启后丢失)

适合仅需要同一次程序运行过程中记住上次输入的场景,实现最简单:

namespace Project2
{
    public partial class Form2 : Form
    {
        // 静态变量全局唯一,不会随窗体实例销毁而清除
        private static decimal _lastNumericValue = 0;

        public Form2()
        {
            InitializeComponent();
            // 窗体初始化时赋值
            numericUpDown1.Value = _lastNumericValue;
            label2.Text = "N: " + _lastNumericValue;
            // 绑定窗体关闭事件,也可以手动在设计器里添加
            this.FormClosing += Form2_FormClosing;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            decimal a = numericUpDown1.Value;
            label2.Text = "N: " + a;
            // 点击按钮时更新存储值
            _lastNumericValue = a;
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 窗体关闭时同步保存最新值,避免未点击按钮直接关闭导致值丢失
            _lastNumericValue = numericUpDown1.Value;
        }
    }
}

方案2:应用设置持久化存储(程序重启后仍可保留)

需要永久保存数值、重启程序也能读取上次输入的场景使用:

  1. 右键项目 -> 点击「属性」-> 切换到「设置」标签页
  2. 新增设置项:名称填LastNumericValue,类型选择decimal,范围选择User,默认值填0,保存项目属性
  3. 修改Form2代码如下:
namespace Project2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            // 读取配置中的存储值
            numericUpDown1.Value = Properties.Settings.Default.LastNumericValue;
            label2.Text = "N: " + Properties.Settings.Default.LastNumericValue;
            this.FormClosing += Form2_FormClosing;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            decimal a = numericUpDown1.Value;
            label2.Text = "N: " + a;
            // 更新配置并持久化保存
            Properties.Settings.Default.LastNumericValue = a;
            Properties.Settings.Default.Save();
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.LastNumericValue = numericUpDown1.Value;
            Properties.Settings.Default.Save();
        }
    }
}

内容的提问来源于stack exchange,提问作者DariusMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:27:03