c# - C# - 如何在用户设置中保存文本框和复选框
问题描述
我有一个 Windows 窗体应用程序,用户可以在其中将数字输入三个不同的文本框。我想通过选中旁边的复选框来保存这些数字,因此当应用程序关闭并重新打开时,您不必再次输入数字。
我已将属性添加到用户设置并实现了下面的代码,但是当我输入一个数字并重新打开应用程序时,什么都没有显示,它们也没有保存在 user.config 文件中。
非常感谢任何帮助,因为我找不到我的错误。
private void MainForm_Load(object sender, EventArgs e)
{
Text = Properties.Settings.Default.title;
chkBox1.Checked = Properties.Settings.Default.checkBox;
chkBox2.Checked = Properties.Settings.Default.checkBox;
chkBox3.Checked = Properties.Settings.Default.checkBox;
txtBox1.Text = Properties.Settings.Default.textBox;
txtBox2.Text = Properties.Settings.Default.textBox;
txtBox3.Text = Properties.Settings.Default.textBox;
this.Location = new System.Drawing.Point(Properties.Settings.Default.PX, Properties.Settings.Default.PY);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.checkBox = chkBox1.Checked;
Properties.Settings.Default.checkBox = chkBox2.Checked;
Properties.Settings.Default.checkBox = chkBox3.Checked;
Properties.Settings.Default.textBox = txtBox1.Text;
Properties.Settings.Default.textBox = txtBox2.Text;
Properties.Settings.Default.textBox = txtBox3.Text;
Properties.Settings.Default.PX = this.Location.X;
Properties.Settings.Default.PY = this.Location.Y;
Properties.Settings.Default.Save();
}
private void chkBox1_Checked(object sender, EventArgs e)
{
this.Text = txtBox1.Text;
}
private void chkBox2_Checked(object sender, EventArgs e)
{
this.Text = txtBox2.Text;
}
private void chkBox3_Checked(object sender, EventArgs e)
{
this.Text = txtBox3.Text;
}
解决方案
为什么不使用数据绑定来自动保存更改。您不需要在 form_load 和 form_closing 事件上复制代码。
我对控件数据绑定的最好解释是它们提供了控件属性和对象属性之间的两种模型更新方式。更多信息https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.databindings?view=netcore-3.1
private void Form1_Load(object sender, EventArgs e)
{
chkBox1.DataBindings.Add("Checked", Properties.Settings.Default, "Checked1",true, DataSourceUpdateMode.OnPropertyChanged);
chkBox2.DataBindings.Add("Checked", Properties.Settings.Default, "Checked2",true, DataSourceUpdateMode.OnPropertyChanged);
chkBox3.DataBindings.Add("Checked", Properties.Settings.Default, "Checked3",true, DataSourceUpdateMode.OnPropertyChanged);
//you can others
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//don't forget to call save on form closing
Properties.Settings.Default.Save();
}
推荐阅读
- angular-in-memory-web-api - “Angular-in-memory-web-api”中的 genId() 方法
- model - 同步电机状态空间方程的局部化
- php - 超过渐变时,Tcpdf multiCell 边框丢失
- javascript - Ionic 4+ 推送通知自定义参数
- python - bin 中出现的总和
- machine-learning - numpy elementwise 相乘向量和矩阵具有相同的行数
- kubernetes - Ratelimit 部署中每秒创建的 Pod 数量
- docker - Linux 和 Windows 上的 Docker-Compose 有区别吗?
- c# - 在加载时将值从 InputForm 传递到 MainForm
- swift - swift 5 中的可选闭包