How do you get the text from two textboxes to populate a listbox on a Windows Form Application? 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"); 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. See below.
EDITED: Added way to add the Text
to the ListBox
and still clear the TextBox
controls afterwards.
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. Whats the point exactly?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.