【问题标题】:How can I code to retain the data even after its closed?即使在数据关闭后,我如何编码以保留数据?
【发布时间】:2019-10-11 15:15:13
【问题描述】:

我对 c# 和 winforms 比较陌生,我需要一些编码帮助来解决问题。 我创建了一个带有 4 个文本框的 winform,并使用保存按钮在 xml 中序列化了这些数据。实际的问题是:如何反序列化数据,因为这些项目返回到它们各自的文本框。如果我关闭并打开整个应用程序,文本框中的数据应该被保留。

目标:即使在关闭并再次打开后,如何使数据保留在应用程序(文本框)中。这里我不应该使用任何数据库

【问题讨论】:

  • 将 xml 保存在 .xml 文件中,然后将 xml 读取并反序列化到对象中。
  • 您需要将文本框名称映射到 xml 标签。最简单的方法是使xml标签名称与文本框名称相同。

标签: c# xml winforms serialization deserialization


【解决方案1】:

实现这一点的唯一方法是将数据绑定到应用程序设置变量。

  1. 将每个文本框绑定到其自己的应用程序设置变量,注意将它们创建为用户范围(默认),而不是应用程序范围。
  2. 注册一个 Form_Closing 事件处理程序,并让它保存设置。

以下是我在 2005 年编写并每天使用的生产 C# 程序中的 Form_Closing 事件例程。

private void frmMain_FormClosing ( object sender , FormClosingEventArgs e )
{   // Update user settings, even if the cmdQuit_Click event was bypassed.
    if ( _intDesiredWidth > STRING_IS_EMPTY )
    {
        int intDefaultDesiredWidth;

        if ( int.TryParse ( Properties.Settings.Default.DesiredWidth , out intDefaultDesiredWidth ) )
        {
            if ( _intDesiredWidth != intDefaultDesiredWidth )
            {
                Properties.Settings.Default.DesiredWidth = _intDesiredWidth.ToString ( );
                Properties.Settings.Default.Save ( );   // Save only when there is something worth saving.
            }   // if ( _intDesiredWidth != intDefaultDesiredWidth )
        }   // if ( int.TryParse ( Properties.Settings.Default.DesiredWidth , out intDefaultDesiredWidth ) )
    }   // if ( _intDesiredWidth > STRING_IS_EMPTY )
}   // private void frmMain_FormClosing

【讨论】:

  • 这绝对不是唯一的方法。
猜你喜欢
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多