C#逐个添加字符串列表,每次更新显示列表

时间:2018-03-08 16:47:10

标签: c# list windows-forms-designer

我的最终目标是能够逐个将文字输入到文本框中,并在每次输入代码时将它们显示在更新的按字母顺序排列的列表中。我对此很新,对任何错误都很抱歉!

namespace SortWords2
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        label1.Text = String.Empty;

    }

    private void button1_Click(object sender, EventArgs e)
    {

        string newWord;
        newWord = textBox1.Text;
        addToList(newWord);
    }

    public  void addToList(string word)
    {
        List<string> inputList = new List<string>();
        inputList.Add(word);
        inputList.Sort();
        foreach(string words in inputList)
        {
            label1.Text += "\r\n" + words;
        }
    }
}
}

在当前状态下,它只是添加输入字,然后跳到下一行,让我添加另一个字。所以我甚至不确定我是否在制作一个列表,我认为它只是添加了当前的单词。

2 个答案:

答案 0 :(得分:2)

为您的班级创建一个私人列表,并按下按钮,将新字符串添加到您的私人列表中:

public partial class Form1 : Form
{
    //Declare private list of type string as class property, this maintains
    //scope in all methods of class object
    private List<string> inputList;
    public Form1()
    {
        InitializeComponent();
        label1.Text = String.Empty;
        //Initialize your list
        this.inputList = new List<string>();
    }

现在点击按钮方法:

public  void addToList(string word)
    {
        //Remove this next line as you are appending to your class's list
        //and you initialized it in your constructor
        //List<string> inputList = new List<string>();
        inputList.Add(word);
        inputList.Sort();
        foreach(string words in inputList)
        {
            label1.Text += "\r\n" + words;
        }

        //If you really want to get funky, you can do the linq llambda way of appending to your label
       //inputList.ForEach(x => label1.Text += "\r\n" + x);
    }

答案 1 :(得分:0)

//this exists at the **class** level, outside of a function
private List<string> inputList = new List<string>();

private void button1_Click(object sender, EventArgs e)
{
    addToList(textBox1.Text);
}

public  void addToList(string word)
{
    inputList.Add(word);
    inputList.Sort();

    label1.Text = string.Join(Environment.NewLine, inputList);
}