我有以下問題。我正在使用 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;
}
}
}
但是打開之后還是空的。
uj5u.com熱心網友回復:
您可以使用static variable來存盤上次更新的值,并且通過類名的參考,您可以隨時隨地使用它。
來自 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;
}
}
}
uj5u.com熱心網友回復:
在這種情況下,您可以使用以下內容創建一個為 NumericUpDown 控制元件提供設定/獲取的類。
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;
}
}
上面的代碼,特別是 Settings 類被稱為單例模式,您可以在在 C#中實作單例模式中了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/327201.html
