jolly
jolly

Reputation: 285

Append Text Insert to ListBox or ComboBox1

I have a richTextBox1 with this line:

my test
my test2 

and tried to use this code to insert the lines in to a listbox or combox:

richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString();
listBox1.Items.Add(richTextBox1.Text);

but the listbox displays

mytestmytest2

How do I insert (append) each item as a new line?

Upvotes: 0

Views: 26125

Answers (3)

Taufiq Abdur Rahman
Taufiq Abdur Rahman

Reputation: 1388

richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString();
listBox1.Items.AddRange(richTextBox1.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None));

You dont need a loop in insert all the items. this can be done by using Items.AddRange

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94653

To add a string one after one, use File.ReadAllLines() method.

string []lines=System.IO.File.ReadAllLines("file.txt");

    foreach(string str in lines)
     {
      listBox1.Items.Add(str);
     }

Another way to draw text is to set DrawMode=OwnerDrawVariable and handle the DrawItem event to draw the text.

Upvotes: 1

Polity
Polity

Reputation: 15130

You should split the text coming from richTextBox1 based on line feeds. If you want multiple items in your listbox, you should call Items.Add for each item.

Example:

richTextBox1.Text = File.ReadAllText(@"New ID.txt").ToString(); 

foreach (string line in richTextBox.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
{
    listBox1.Items.Add(line); 
}

Upvotes: 5

Related Questions