VB.NET textbox to listbox new line

Asked at 2017-01-11 20:44:42Z
  • 5 Subscribers
  • 114 Views
0

I have a list of 4 digit extensions that I'm pulling out of my server

cmd = sshClient.RunCommand("asterisk -x 'sip show peers' | grep -w OK | awk '{print $1}' | awk -F'/' '{print $1}'")
TextBox1.Text = cmd.Result

TextBox1 does fill up with the extension list, but it is all in 1 line

(btw, if I change it from TextBox1 to Label1, then I get them in separate lines)

Then, with button2 (to get the list into a ListBox) I have

Dim ext As String
ext = TextBox1.Text
ListBox1.Items.Add(ext)

But I get the list in 1 item and no spaces (it doesn't mater if it is from the TextBox or Label)

I tried adding

If TextBox1.Text.Length > 4 Then TextBox1.Text = TextBox1.Text.Insert(4, Environment.NewLine)

But it adds a new line for the first 4 digits (1 extension) only, the rest are in 1 line

Any idea?

Thanks


2 answers in total

1
Chris R. Timmons Posted at 2017-01-11 21:01:40Z

The string data returned by asterisk is probably separated by line feeds (ASCII value of 10). Split the return string on Chr(10) and use the .AddRange(ext) function to add all of the items to the listbox:

ListBox1.Items.AddRange(ext.Split(New Char() {Chr(10)}, StringSplitOptions.RemoveEmptyEntries))
0
Elemental Pete Posted at 2017-01-11 20:58:30Z

The answer will vary a bit depending on whether you are using WinForms, WPF, etc - I am assuming WinForms.

Check that your textbox is set to Multiline = true - if not, that may fix your first problem. But more fundamentally, @LarsTech is on the right track. Assign cmd.Result to a new string variable (instead of directly to TextBox1.Text) then split it into a string array with String.Split(), then loop through the array adding each one separately to your ListBox individually. You won't be able to get multiple items into a Listbox with a single Items.Add statement regardless of how you handle your line breaks.

If that is all that your loop is doing, then you can use ListBox.AddRange() to add the whole array at once.

Answer this questsion