user1017524
user1017524

Reputation: 241

When I save items in a listbox there are too many lines in between

I need help in a little feature in my program.

My program gets items from a website then saves it to a listbox. From that listbox it transfers it to another listbox putting the items, each in their own line.

From there I save the file in a text file.

When I check the file on my desktop there are two lines in between each item even though in my listbox it didnt show any items in between. Can you help?

Here is the code to add the items to the other listbox:

listBox6.Items.Add(listBox5.SelectedItem.ToString() + ":" + txtBox2.Text + Environment.NewLine);

Here is the code to save the listbox items:

    StreamWriter Write;
    SaveFileDialog Open = new SaveFileDialog();
    try
    {
        Open.Filter = ("Text Document|*.txt|All Files|*.*");
        Open.ShowDialog();
        Write = new StreamWriter(Open.FileName);
        for (int I = 0; I < listBox6.Items.Count; I++)
        {
            Write.WriteLine(Convert.ToString(listBox6.Items[I]));
        }
        Write.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(Convert.ToString(ex.Message));
        return;
    } 

Upvotes: 1

Views: 274

Answers (2)

M.Babcock
M.Babcock

Reputation: 18965

Better yet remove the explicit new line:

listBox6.Items.Add(listBox5.SelectedItem.ToString() + ":" + txtBox2.Text)

Upvotes: 1

Andrey Shchekin
Andrey Shchekin

Reputation: 21619

Replace Write.WriteLine with Write.Write since you already added Environment.NewLine before.

Upvotes: 4

Related Questions