如何在 C# 中关闭程序后保存复选框、文本框等的状态
在我用 Visual Studio 2010 制作并使用 WinForms 的 C# 程序中,我希望程序保存某些复选框和文本框的状态,以便下次加载程序时将它们选中或取消选中,就像上次运行的状态一样。文本框等内的字符串也相同...
实现此目的的正确方法是什么? .NET 中有内置的东西吗?任何提示和代码片段将不胜感激!
谢谢
In my C# program that is made with Visual Studio 2010 and uses WinForms, I would like the program to save state of some checkboxes and textboxes so the next time program will be loaded they are checked or unchecked as theire last run's state. Also same with strings inside textboxes and etc...
What will be the proper way to achieve this? Is there a built in stuff in .NET? Any tips and code snippets would be appriciated!
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能希望在 FormClosing 事件期间从 UI 中读取相关值,然后将它们保存到用户设置中。
看一下:http://codehill.com /2009/01/在winforms中保存用户和应用程序设置/
You'd probably want to look at reading the relevant values from your UI during the FormClosing event, and then saving them into User Settings.
Have a look at: http://codehill.com/2009/01/saving-user-and-application-settings-in-winforms/
我会将值绑定到用户设置,并保存配置 OnClose 事件。
I would bind the value to user settings, and saving the configuration OnClose event.
实现此目的的一种方法是使用 XML 配置文件并将其序列化:
ConfigManager.cs
应用程序中的某处
private ConfigManager cm;
private XmlSerializer ser;
...
然后您必须加载配置:
要保存它:
One way to do this is using an XML configuration file and serializing it:
ConfigManager.cs
somewhere in your application
private ConfigManager cm;
private XmlSerializer ser;
...
Then you have to load the configuration:
To save it:
你问了一个非常广泛的问题。有两种看待它的方法。
1) 如果您需要保留应用程序级别配置,最好的选择是使用 应用程序设置。人们可以序列化用户使用您的应用程序完成的程序设置,并在程序重新启动后恢复它们。这适用于 WinForms 和 WPF:
2) 如果您需要用户级持久性,则需要 用户设置。
此外,您还可以创建自定义类来实现存储您需要的所有配置属性。
实现 ISerialized 并将其标记为 [Serializable]。您可以将其标记为[Serialized],但如果将来添加新属性,则会遇到反序列化问题。
添加版本属性。
添加两个静态方法:Load 和 Save。这些方法使用isolatedStorage将配置类反序列化/序列化到磁盘。您可以使用任何您想要的序列化 - 我使用二进制。为什么不使用 XML?因为二进制速度更快,并且用户永远不需要进入这些文件。我曾经在 .net 2.0 中这样做过。
You asked very broad question. there are two ways to look at it.
1) If you have a need to persist application level configuration, your best bet is to use Application Settings. One can serialize program settings the user has done using your app, and restore them after the program has restarted. This works with WinForms and WPF:
2) If you need user level persistence, you need user settings.
Also, you can create custom class that implements that stores all of the configuration properties that you need.
Implement ISerializable and mark it [Serializable]. You could just mark it [Serializable], but if you add new properties in the future, you'll run into deserialization problems.
Add a Version property.
Add two static methods: Load and Save. These methods use IsolatedStorage to deserialize/serialize your configuration class to disk. You can use any kind of serialization you want - I use binary. Why not XML? Because binary is faster and users never need to get into these files. I used to do this for .net 2.0.