[RESOLVED] Multiline textbox to listbox
I have a multiline textbox with text that i want to add to a listbox. Each line in the textbox should be a new line in the listbox.
I had a problem when going from listbox to textbox but that was solved with
VB.NET Code:
For Each item As String In EnDeCrypt.ListBox1.Items
EnDeCrypt.TextBox1.AppendText(item & Environment.NewLine)
Next
Is it adaptable to do what i'm trying to do now?
If not then how would i do it.
Thanks ;)
Re: Multiline textbox to listbox
Going from the TextBox to the ListBox is easier:
vb.net Code:
myListBox.Items.AddRange(myTextBox.Lines)
or:
vb.net Code:
myListBox.DataSource = myTextBox.Lines
If the list already contains items that you want to keep then use the first, otherwise I'd probably use the second.
Re: Multiline textbox to listbox
Okay, after messing around a bit i came up with this.
vb Code:
ListBox1.Items.Add(TextBox1.Lines(0))
That copies the first line of the textbox into the list box.
So now i need a way to get the number of lines in the textbox (since it can vary).
I know the code to do this..
vb Code:
Dim line As String
line = TextBox1.Lines.Count
TextBox2.Text = line
But, it returns the actual value. (It returns 7 since for my test i)
-------
Stopping there since i got an email for a reply to this thread.
Read it.. and i found i made this out to be a lot harder than it is haha.
Thanks for your help, works perfectly.
Re: Multiline textbox to listbox
thats because Lines.Count is the actual number like you said, so you should expect it to be 7. What you need to do is combine both the add line code and the line.Count code in a Loop.
Code:
For X as Integer = 0 to TextBox1.Lines.Count - 1
ListBox1.Items.Add(TextBox1.Lines(X))
Next
That will loop through each textbox line and add it to the listbox.
Re: Multiline textbox to listbox
Quote:
Originally Posted by
Vectris
thats because Lines.Count is the actual number like you said, so you should expect it to be 7. What you need to do is combine both the add line code and the line.Count code in a Loop.
Code:
For X as Integer = 0 to TextBox1.Lines.Count - 1
ListBox1.Items.Add(TextBox1.Lines(X))
Next
That will loop through each textbox line and add it to the listbox.
Ahhh i see.
Thanks :)
Re: [RESOLVED] Multiline textbox to listbox
If you were going to add them one by one then the actual number would irrelevant because you know you've just got to do it once for each, so you'd use a For Each loop, not a For loop:
vb.net Code:
For Each line As String In myTextBox.Lines
myListBox.Items.Add(line)
Next
It is almost always the case that, if all you would use the loop counter for is to index a single list, then you should be using a For each loop rather than a For loop. Of course, you wouldn't add them one by one because it's easier and more efficient to add them all together using AddRange.