制作一个按钮,为下次程序运行保存列表



我正在制作一个windows窗体应用程序。它是一个单词生成器,从默认列表中生成一个随机单词,该列表也可以由用户输入修改。我正在寻找一种方法,使它使一个按钮将保存列表,以便下次用户运行应用程序时,他们将有从以前相同的列表。Txtaddverb是用于用户输入的文本框。缺少的按钮只对名词、形容词和副词列表执行相同的操作。

下面是我的代码:
  public class Lists
    {
        public static List<string> verbList = new List<string>() {"eat", "scramble", "slap", "stimulate"};
        public static Random randomverb = new Random();
    }

public string pickRandomVerb()
        {
            return Lists.verbList[Lists.randomverb.Next(0, Lists.verbList.Count)];
        }
public void button1_Click(object sender, EventArgs e)
        {
            if (Lists.verbList.Count > 0) verb.Text = pickRandomVerb();
        }
public void button5_Click(object sender, EventArgs e)
        {
            Lists.verbList.Add(txtaddverb.Text);
            txtaddverb.Clear();
        } 
public void button9_Click(object sender, EventArgs e)
        {
            Lists.verbList.Clear();
            verb.Clear();
            txtaddverb.Clear();
        }
//below is the button that I want to save the list
public static void button13_Click(object sender, EventArgs e)
        {
            //need help here
        }

看情况。您希望将输入保存在哪里?在文本文件中?在数据库中?

保存到文本文件的示例

        // create a writer and open the file
        TextWriter tw = new StreamWriter("date.txt");
        // write a line of text to the file
        tw.WriteLine(DateTime.Now);
        // close the stream
        tw.Close();

List<string>写入文件:

File.WriteAllLines(path, verbList);

如果该文件不存在,将创建该文件,否则将覆盖该文件。

从文件中读取:

List<string> verbList = File.ReadAllLines(path).ToList();

如果这个项目更适合个人使用,那么您可以将列表写入文本文件,并在程序加载时将其读取回来。streamreader和streamwriter类可以为此实现。参见http://msdn.microsoft.com/en-us/library/aa903247%28v=vs.71%29.aspx获取一些示例代码。

如果有很多人使用你的应用程序,我会说将列表保存到数据库将是一个更好的解决方案。这是一个开始的好地方http://www.dreamincode.net/forums/topic/31314-sql-basics-in-c%23/#/如果你没有SQL服务器教程可以调整像MS Access。(您将使用System.Data.OleDb而不是System.Data.SqlClient)

有很多文章讨论如何将信息读取和写入文本文件或数据库。做一点搜索,你应该能够找到一些适合你的需要,如果我发布的两个链接没有什么你正在寻找。

相关内容

最新更新