Reputation: 285
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
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
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
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