Listbox1 add all the items to richtextbox in the same format - vb.net

I'm trying to get all the ListBox1 items and have them go to the RichTextBox1. I want it in the same format that it's in the ListBox1. I've tried different code and they seem to give extra blank lines in between items. So far I've thought of this but it give extra blank lines.
Dim counter As String
counter = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem
Loop
End If

Use LINQ to select all the items and join on Environment.NewLine:
.Net >= 4.0
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()))
.Net >= 3.5
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()).ToArray())

you are adding a vbNewLine before you add the ListBox text... you should put that at the end of the line RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine and you also shouldn't increment your selected index value until after you add the line...
Alternatively, You can do this..
For i = 0 To ListBox1.Items.Count - 1
RichTextBox1.Text = RichTextBox1.Text & ListBox1.Items(i) & vbCrLf
Next
OR this SO question has a few good examples using LINQ and condensed query code...
passing all the items of listbox in the richtextbox

This is because initially the richtextbox is empty. Hence RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem will add a New Line first and the add the second element of list to the richtextbox, this is because you incremented the selected index value by 1 before adding to the richtexbox. So your code can be used in an effective way as follows:
Dim counter As Integer = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
Loop
End If

try saving the listbox to a file using a streamwriter and writeline(), then opening it into a text box using streamreader and readtoend()
'assuming you have the default names
dim reader As streamreader, writer As streamwriter
writer = new streamwriter("TMP")
for each x as object in listbox1.items
writer.writeline(X)
next
writer.close()
reader=new streamreader("TMP")
textbox1.text=reader.readtoend()
reader.close()

Related

Index was outside the bounds of the array. VB.NET

My problem
Index was outside the bounds of the array. when i try to run the code , it generates this error
i have two forms : SIGN IN and SIGN UP , my problem is they don't work together and generates the error attached below
Dim fs As New FileStream("C:\Users\Selmen\Desktop\vb\logs.txt", FileMode.Open, FileAccess.ReadWrite)
Dim sr As New StreamReader(fs)
Dim sw As New StreamWriter(fs)
Dim s As String
Dim t() As String
Dim trouve As Integer = 0
Dim tt() As String
Dim ch As String
ch = TextBox1.Text + "#" + TextBox2.Text + "#" + TextBox3.Text + "#" + TextBox4.Text + "#" + TextBox5.Text
tt = ch.Split("#")
Do While (trouve = 0) And (sr.Peek > -1)
s = sr.ReadLine
t = s.Split("#")
If String.Compare(t(2), tt(2)) = 0 Then
trouve = 1
End If
Loop
If (trouve = 1) Then
MsgBox("user existant")
Else
sw.WriteLine(ch)
Me.Hide()
Form4.Show()
End If
sw.Close()
sr.Close()
fs.Close()
End Sub
If String.Compare(t(2), tt(2)) = 0 Then I get:
IndexOutOfRangeException was unhandled / Index was outside the bounds of the array.
Streams need to be disposed. Instead of using streams you can easily access a text file with the .net File class.
File.ReadAllLines returns an array of lines in the file. We can loop through the lines in a For Each. The lower case c following the "#" tells the compiler that you intend a Char not a String. String.Split expects a Char. Normally, String.Compare is used to order strings in alphabetical order. You just need an =. As soon as we find a match we exit the loop with Exit For.
We don't actually need the array of the text boxes Text property unless there is no match. Putting the elements in braces intializes and fills the array of String.
File.AppendAllLines does what it says. It is expecting an array of strings. As with the text boxes, we put our line to append in braces.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim p = "path to file"
Dim lines = File.ReadAllLines(p)
Dim trouve As Integer
For Each line In lines
Dim thirdField = line.Split("#"c)(2)
If thirdField = TextBox3.Text Then
trouve = 1
Exit For
End If
Next
If trouve = 1 Then
MsgBox("user existant")
Else
Dim tt = {TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text}
File.AppendAllLines(p, {String.Join("#", tt)})
Me.Hid3e()
Form4.Show()
End If
End Sub

Comparing text in two Richtextboxes and get the differences

I'm want to compare the text between two richtextboxes and get the differences in the third one. Without highlight the text.
So far, the best option is this solution
The first solution works, but it doesn't remove the text present in richtextbox2 from the richtextbox1.
Endeed, the user asked
if they are the same do nothing.
My case is complete the opposite and still i cannot find a solution.
Thanks
First, you need to add a combobox to your form named (combobox1)
then add these items in it:
RichTextbox1 - RichTextbox2
RichTextbox2 - RichTextbox1
second, add a button named (button1), under this button click event
insert this code:
RichTextBox3.Clear()
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox1 - RichTextbox2" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff1 As String = ""
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff1.ToString
End If
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox2 - RichTextbox1" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff2 As String = ""
For Each diff As String In txt2
If Array.IndexOf(txt1, diff.ToString) = -1 Then
diff2 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff2.ToString
End If
now, you have 2 options:
if you choose (RichTextbox1 - RichTextbox2) from the combobox then click the button, richtextbox3 will display the text which is found in richtextbox1 and not found in richtextbox2, while if you choose (RichTextbox2 - RichTextbox1), the opposite will happen
finally, if the 2 richtextboxes is the same, nothing will occur
Also you could use String.Join *
Under Button1 click event replace this code with the previous one:
Dim intsA = RichTextBox1.Text.Split(" ")
Dim intsB = RichTextBox2.Text.Split(" ")
Dim myresult = intsA.Except(intsB).ToArray()
RichTextBox3.Text = String.Join(" ", myresult)
if you found this useful, mark it as answer

Split multi line in VB

I have a problem in split multi line in that it only splits the first line. I want to split all the lines.
Dim a As String
Dim b As String
Dim split = TextBox1.Text.Split(":")
If (split.Count = 2) Then
a = split(0).ToString
b = split(1).ToString
End If
TextBox2.Text = a
TextBox3.Text = b
You have to iterate all the lines in the textbox
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
TextBox2.Text &= Lines(0) & Environment.NewLine
TextBox3.Text &= Lines(1) & Environment.NewLine
End If
End If
Next
Edit- Updated to include condition checking to prevent index exceptions.
Edi2- It should be mentioned that drawing your strings into these textbox controls can take some time, it's not my place to judge your requirement, but you could optimize the routine by using collection based objects or stringbuilder.
IE:
Dim StrBldrA As New Text.StringBuilder
Dim StrBldrb As New Text.StringBuilder
For Each Ln As String In TextBox1.Lines
If Not String.IsNullOrEmpty(Ln) Then
Dim Lines() As String = Ln.Split(":"c)
If Lines.Length = 2 Then
StrBldrA.Append(Lines(0) & Environment.NewLine)
StrBldrb.Append(Lines(1) & Environment.NewLine)
End If
End If
Next
TextBox2.Text = StrBldrA.ToString
TextBox3.Text = StrBldrb.ToString

VB Saving Listview Items Error

Well the code itself works. The problem occurs when there is a sub items without text, the program will crash. I'm looking for a method that will bypass this annoying error.
My Code:
If ComboBox1.Text = "Everything" Then
Dim SetSave As SaveFileDialog = New SaveFileDialog
SetSave.Title = ".txt"
SetSave.Filter = ".txt File (*.txt)|*.txt"
If SetSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim s As New IO.StreamWriter(SetSave.FileName, False)
For Each myItem As ListViewItem In Form1.ListView1.Items
s.WriteLine(myItem.Text & TextBox1.Text & myItem.SubItems(1).Text & TextBox1.Text & myItem.SubItems(2).Text & TextBox1.Text & myItem.SubItems(3).Text & TextBox1.Text & myItem.SubItems(4).Text & TextBox1.Text & myItem.SubItems(5).Text & TextBox1.Text & myItem.SubItems(6).Text & TextBox1.Text & myItem.SubItems(7).Text) '// write Item and SubItem.
Next
s.Close()
End If
Error:(this indicates the the listview item without text it can range from number 1 up to 7, the one below is 5)
InvalidArgument=Value of '5' is not valid for 'index'.
Parameter name: index
Your indexing is starting at 1. VB indexing starts at 0 so for 5 items you whould have index values of 0 to 4

Exclude records from the first and last rows in a loop

Below is my export to csv from listview using vb.net
Function ExportListview2CSV(ByVal lstview As ListView) As Boolean
Dim saveFileDialog1 As New SaveFileDialog()
Dim csvFileContents As New System.Text.StringBuilder
Dim CurrLine As String = String.Empty
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.Title = "Save an CSV File"
csvFileContents.AppendLine("Service Provider Name: |" & cbodestproname.Text)
'csvFileContents.AppendLine(cbodestproname.Text)
csvFileContents.AppendLine("Circel Name: |" & cbodestcirclename.Text)
'csvFileContents.AppendLine(cbodestcirclename.Text)
csvFileContents.AppendLine("Month: |" & dtpDate.Text)
' csvFileContents.AppendLine(dtpDate.Text)
csvFileContents.AppendLine("Type of File: |" & cbotypeoffile.Text)
' csvFileContents.AppendLine(cbotypeoffile.Text)
csvFileContents.AppendLine("")
'Write out the column names as headers for the csv file.
For columnIndex As Int32 = 1 To lstview.Columns.Count - 2
CurrLine &= (String.Format("{0}|", lstview.Columns(columnIndex).Text))
Next
'Remove trailing comma
csvFileContents.AppendLine(CurrLine.Substring(0, CurrLine.Length - 1))
CurrLine = String.Empty
'Write out the data.
For Each item As ListViewItem In lstview.Items
For Each subItem As ListViewItem.ListViewSubItem In item.SubItems
CurrLine &= (String.Format("{0}|", subItem.Text))
Next
'Remove trailing comma
csvFileContents.AppendLine(CurrLine.Substring(0, CurrLine.Length - 1))
CurrLine = String.Empty
Next
'Create the file.
If saveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If saveFileDialog1.FileName <> "" Then
Dim Sys As New System.IO.StreamWriter(saveFileDialog1.FileName)
Sys.WriteLine(csvFileContents.ToString)
Sys.Flush()
Sys.Dispose()
MsgBox("Data's are Saved Succesfully to " & saveFileDialog1.FileName, MsgBoxStyle.Information)
End If
End If
End Function
i want to exclude the records from the 1st and last rows
where should i make chages in above code
plz help me
thanx in advance.
You might use
For i as Integer = 1 to lstview.Items.Count - 2
...
Next
that will start from the second item and stop before the last item
yeah, you should use an index other than for each to iterate the items in listview