简体   繁体   English

从2个文本框中填充列表框

[英]populate listbox from 2 textboxes

How do you get the text from two textboxes to populate a listbox on a Windows Form Application? 如何从两个文本框中获取文本以填充Windows窗体应用程序上的列表框? I can not get the text that is put into the textboxes to go to the listbox. 我无法获取放入文本框以转到列表框的文本。

This is the code I got so far: 这是我到目前为止得到的代码:

       private void Form1_Load(object sender, EventArgs e)
    {
        if (File.Exists("Contacts.txt"))
        {
            StreamReader Info = new StreamReader("Contacts.txt");
            listBox1.Items.Clear();
            while (Info.EndOfStream != true)
                listBox1.Items.Add(Info.ReadLine());
            Info.Close();
        }
    }


    private void button1_Click(object sender, EventArgs e)
    {

        listBox1.Items.Add(textBox1.Text);
        listBox1.Items.Add(textBox2.Text);
        textBox1.Clear();
        textBox2.Clear();
        Console.WriteLine("/n");
    }

But that Console.WriteLine("/n"); 但是那个Console.WriteLine(“ / n”); does not put a space between the next entry of the textboxes 在文本框的下一个条目之间不留空格

You need to call Add() with the Text property of the TextBox not the text box itself. 您需要使用TextBoxText属性而不是文本框本身来调用Add() See below. 见下文。

EDITED: Added way to add the Text to the ListBox and still clear the TextBox controls afterwards. 编辑:添加了将Text添加到ListBox并随后仍然清除TextBox控件的方法。

private void button1_Click(object sender, EventArgs e)
{
    StreamWriter Info = File.AppendText("Contacts.txt");

    string textbox1Content = textbox1.Text;
    string textbox1Content = textbox2.Text;


    listBox1.Items.Add(textbox1Content);
    listBox1.Items.Add(textbox1Content);

    textBox1.Text = String.Empty;
    textBox2.Text = String.Empty;

}

Also I don't understand your for loop... it only executes one time. 我也不明白你的for循环...它只会执行一次。 Whats the point exactly? 到底是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM