Append Text Insert to ListBox or ComboBox1

23,983

Solution 1

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); 
}

Solution 2

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

Solution 3

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.

Share:
23,983
jolly
Author by

jolly

Updated on July 07, 2022

Comments

  • jolly
    jolly almost 2 years

    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?