【问题标题】:Load, Save and Read data in textboxes when ap is opened & closed c# VS 2012打开和关闭 ap 时在文本框中加载、保存和读取数据 c# VS 2012
【发布时间】:2013-02-25 13:59:17
【问题描述】:

我有一个应用程序,用户登录到一个文本框列表,用户可以在其中写入数据,然后关闭应用程序,当他们打开它时,数据仍在文本框中。

我一直在研究 .txt 和 .xml 以了解哪种格式最适合使用。我还研究了 XML 序列化以及 .xml 文件中包含哪些代码,但我有点迷失了,我是否必须更改文本框的名称才能将数据加载到正确的框中?页面本身大约有 15 个文本框。

我使用 System.Xml.Serialization 添加了;到我的表格。 此外,当用户登录时,它会打开一个现有的表单,而当用户注销时,它只会关闭表单。

我有点困惑如何加载显示所有数据的页面、保存数据(我为文本框页面创建了一个保存按钮)以及读取文件不是读取和加载相同的吗?

我正在使用 Visual Studio 2012 Winforms c#

【问题讨论】:

  • 应该是用户特定的吗?如果是这样,使用数据库的方法可能会更好。你试过什么?请显示一些代码

标签: c# winforms textbox xml-serialization


【解决方案1】:

您可以使用 XML 的属性并从用户登录名中为其命名。

static public void CreateFile(string username)
{
    XmlWriter xmlW = XmlWriter.Create(username + ".xml");
    xmlW.WriteStartDocument();
    xmlW.WriteStartElement("Listofboxs");

//add the box following this canvas
    xmlW.WriteStartElement("box");
    xmlW.WriteAttributeString("nameofbox", "exampleName");
    xmlW.WriteAttributeString("valueofbox", "exampleValue");
    xmlW.WriteEndElement();
   //
    xmlW.WriteEndElement();
    xmlW.WriteEndDocument();
    xmlW.Close();
}

这将允许您使用用户名创建第一个文件。 其次,要在重新加载应用程序时显示这些信息,这里有一些代码:

static public Dictionary<string, string> getBoxValue(string username)
{
     Dictionary<string, string> listofbox = new Dictionary<string, string>();

    XmlDocument xmldoc = new XmlDocument();
    xmldoc.Load(@"./" + username + ".xml");
    XmlNode root = xmldoc.DocumentElement;

    foreach (XmlNode box in root)
    {
 listofbox.Add(box.Attributes[0].Value.ToString(),box.Attributes[1].Value.ToString()); 
    }
return listofbox;
}

对于每个节点,字典将添加一对字符串,框的名称及其值。 你可以用它来填满你的盒子。 我知道这段代码可能有点效率低下(应该使用“使用”等),但我希望它可以帮助你。

【讨论】:

    【解决方案2】:

    我无法完全理解您的问题。显示您想要的程序的编码。 只需在您的页面加载时尝试清除所有文本框数据。

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
        }
    

    【讨论】:

    • 这并不能远程执行 OP 的要求。以后,如果您不了解确切用户在问什么,请不要发布答案。
    【解决方案3】:

    要读取和写入 xml 文件,您可以将数据集添加到项目中,并在其中定义两列。一列是文本框的名称,另一列是值。在数据集上,您可以使用方法 WriteXml 和 ReadXml 进行读取和写入。

    要在启动时加载 xml,您必须订阅表单的加载事件。并且在 Formclosing-event 中你可以写你的数据。

    public Form1()
    {
       this.Load += OnLoad();
       this.FormClosing += OnFormClosing();
    }
    private void OnLoad(object sender, EventArgs e)
    {
       // Read Data from Xml with the dataset (dataset.Readxml...)
    }
    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
       // Write the Data from the textboxes into the xml (dataset.writexml...)
    }
    

    要设置加载部分中文本框的值,您可以使用以下代码:

    TextBox tb = this.Controls.Find("buttonName", true);
    if(tb != null)
       // set the value for the tb
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2021-11-24
      • 2021-11-22
      • 2021-04-17
      • 1970-01-01
      • 2016-06-22
      相关资源
      最近更新 更多