Displaying each element of array on new line - vb.net

Please consider I am very new with VB.NET when attempting to read and answer my question
I have a textbox that takes in a list of words separated with a comma on the same line. When button is clicked string gets assigned to variable text and I then split it to variable arrayText.
Then I loop over it and display each element of array on new line.
My code looks as follows
Dim text As String
Dim arrayText() As String
text = TextBox1.Text
arrayText = text.Split(",") 'every "," generates new array index, removes ","
text = ""
For i = 0 To arrayText.Length Step 1
text = arrayText(i) & vbCrLf
MsgBox(text)
Next
When debugging I get error message array out of bounds, however when I remove the newline character (vbCrLf) it displays my text, word for word in a messagebox (which I am using for debugging) and at the end of the loop it kicks out with same error message.
What am I doing wrong here, any improvement suggestions?

Though walther answer is right, i suggest you to use a List(Of String) and a For Each...Next loop.
A list is more "modern" and most of the times it is preferred over an array in vb.net. You can use Environment.NewLine instead of vbCrLf. I'm not sure what exactly you want to do, but I dont think that using a MsgBox is the optimal way to present the seperated words. Here is a simple example of what I think you should do :
' Hold the text from the text box.
Dim FullText As String = TextBox1.Text
Dim SeperatedWords As New List(Of String)
' ToList function converts the array to a list.
SeperatedWords = FullText.Split(",").ToList
' Reset the text for re-presentation.
FullText = ""
' Goes through all the seperated words and assign them to FullText with a new line.
For Each Word As String In SeperatedWords
FullText = FullText & Word & Environment.NewLine
Next
' Present the new list in the text box.
TextBox1.Text = FullText

For i = 0 To arrayText.Length - 1 Step 1
Last element has index of length of array - 1.

Related

Saving contents of multiple text boxes and possibly combo boxes

I'm working on a basic application that lets you track experience earned across up to 3 skills. The names of the skills are in a combo box (not sure if the best) and the beginning and ending values are in text boxes.
I want to add a save button that saves the ending values and selected skills, when pressing the load button it would populate the combo boxes with saved skills and input the old ending values into the new beginning ones.
I've been working on this all day, searching for a long time I've come up with similar solutions but nothing seems to work right. I'm still a bit of a beginner so some of the solutions I don't understand. Also, this has to work for VBNet.
The closest solution I've come across is:
File.WriteAllText("C:\Data.txt", String.Join("|", new String({TextBox1.Text, TextBox2.Text, TextBox3.Text}))
I'd like the file to stay with the project in the main directory though. Would this work for combo boxes as well, and how to load the values back in?
I'm still a newbie to VB, hope this question makes sense.
If I get your idea right, please find some functions below if they can help:
One can read (or write) text:
This one can populate the needed string to 3 textboxes txtSkill1, txtSkill2, txtSkill3
Sub ReadTextFile()
Dim lineCount As Integer = 0
Dim rndInstance As New Random
Dim idx As Integer = 0
Dim selectedLine As String = ""
Dim txt As String = "Skills.txt"
If Not File.Exists(txt) Then
File.Create(txt).Dispose()
Dim objWriter As New System.IO.StreamWriter(txt, True)
' 2 sample text lines:
objWriter.WriteLine("Negotiating - Interpersonal - Working independently")
objWriter.WriteLine("Goal oriented - Leadership - Teamwork")
objWriter.Close()
End If
lineCount = File.ReadAllLines(txt).Length
idx = rndInstance.Next(1, lineCount + 1) ' the index can be random if you want, or run from (1 to lineCount)
selectedLine = ReadLineWithNumberFrom(txt, idx)
Dim pattern As String = "-" ' split on hyphens
Dim subStrings() As String = Regex.Split(selectedLine, pattern)
txtSkill1.Text = subStrings(0)
txtSkill2.Text = subStrings(1)
txtSkill3.Text = subStrings(2)
End Sub
One can read a string from a specific line number:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines:
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in:
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeeded!
Return line
End Using
End Function
Now with the functions allow you to write to any text file, to read from any text file, from any line number, with specific separator (here is the hyphen -- char), you can Save and Load any string you need.

Lowercase the first word

Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.

Creating Newlines in PDF with VB.net

I have an application which creates a list from items in a collection. Then for each item, I will add it to an empty string, then add a newline character to the end of it. So ideally my string will look something like:
List1\nList2\nList3\n
Once this string is generated, I send it back to be placed in a placeholder for a pdf. If I try this code in a simple console application, it prints everything on a newline. But in my real world situation, I have to print it to a pdf. The items only show up with spaces in between them and not newlines. How can can format my strings so that pdf recognizes the newline symbol rather than ignoring it?
Here is my code that generates the string with newlines.
Private Function ConcatPlacardNumbers(ByVal BusinessPlacardCollection As BusinessPlacardCollection) As String
Dim PlacardNumbersList As String = Nothing
Dim numberofBusinessPlacards As Long = BusinessPlacardCollection.LongCount()
For Each BusinessPlacard As BusinessPlacard In BusinessPlacardCollection
numberofBusinessPlacards = numberofBusinessPlacards - 1
PlacardNumbersList = String.Concat(PlacardNumbersList, BusinessPlacard.PlacardNumber)
If numberofBusinessPlacards <> 0 Then
PlacardNumbersList = String.Concat(PlacardNumbersList, Enviornment.newline)
End If
Next
Return PlacardNumbersList
End Function
Try to add \u2028 instead:
Private Function ConcatPlacardNumbers(ByVal BusinessPlacardCollection As _
BusinessPlacardCollection) As String
Dim PlacardNumbersList As New StringBuilder()
For Each BusinessPlacard As BusinessPlacard In BusinessPlacardCollection
PlacardNumbersList.Append(BusinessPlacard.PlacardNumber)
'PlacardNumbersList.Append(ChrW(8232)) '\u2028 line in decimal form
PlacardNumbersList.Append(ChrW(8233)) '\u2029 paragr. in decimal form
Next
Return PlacardNumbersList.ToString
End Function
For paragraphs use \u2029instead. Fore more details:
http://blogs.adobe.com/formfeed/2009/01/paragraph_breaks_in_plain_text.html
The answer will depend on the tool that is being used to produce the PDF. Since newline doesn't work, I would actually try \n. The other possibility is that the PDF generation code is not designed to emit multiple lines; you can only determine this by examining the generation code.
However, there is a significant performance issue that you should address in your code: you will be generating a lot of string objects using this code. You should change the design to use System.Text.StringBuilder, which will greatly improve the performance:
Private Function ConcatPlacardNumbers(ByVal BusinessPlacardCollection As BusinessPlacardCollection) As String
Dim PlacardNumbersList As New System.Text.StringBuilder(10000)
For Each BusinessPlacard As BusinessPlacard In BusinessPlacardCollection
If PlacardNumbersList.Length <> 0 Then
' This is equivalent to Environment.NewLine
'PlacardNumbersList.AppendLine()
' The attempt to use \n
PlacardNumbersList.Append("\n")
End If
PlacardNumbersList.Append(BusinessPlacard.PlacardNumber)
Next
Return PlacardNumbersList.ToString
End Function
Note that you also do not need to keep track of the placard number: you can add a newline to the end of the previous item on each pass after the first one.

Find and replace using Listbox Vb.net

ok have a list of 84000 words , and have some articles in these articles i want to replace first occurrence of each word i have in listbox e.g
For Each item In ListBox1.Items
Dim mytext As String = "My some text this text is very long text and i want to replace this"
If ListBox1.Items.Contains(mytext) Then
mytext = Replace(mytext, mytext, "String to replace",Count:=1)
End If
Next
but it used to replace the whole mytext i want to replace words in mytext and also it hang the system and very very slow and help or idea please
It looks like you want to replace everything with the same string, but the code below is easily adaptable to other cases but I go with it for now.
To simplify I am assuming that you want to replace words and the words are only seperated by spaces (' ').
First make a dictionary out of the Items in the listbox:
dim dict = ListBox1.Items.Cast(of object).ToDictionary(function(x) x.ToString())
Then get yourself all words:
dim words = mytext.Split(New [Char](){" "c});
and a word-transform:
dim replaceWith = "your replacement";
dim mapWords as Func(of string,string) = _
function(word) IIf(dict.ContainsKey(word), replaceWith, word)
then transform the words and concatenate them again with ' ':
dim result = String.Join(" ", words.Select(function(word) mapWords(word)))
and you should be done.
If you want to replace with separate words just make the dictionaries values your replacement and switch the mapWords-function with
dim mapWords as Func(of string,string) = _
function(word) IIf(dict.ContainsKey(word), dict(word), word)

Read text file with tab and carraige return format to store them in array

I have to text file in the following format :
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
I want to get all the words before the tab into one array or to create a new text file and the all the words after the tab into another array or create a new text file too.
Here my function to get the words before tab into an array :
Protected Sub MakeWordListBeforeTab()
Dim filename As String = "D:\lao\00001.txt"
'read from file'
Dim MyStream As New StreamReader(filename)
'words before tab
Dim WordBeforeTabArr() As String = MyStream.ReadToEnd.Split(CChar("\t"))
MyStream.Close()
'test to see the word in array
For d As Integer = 0 To WordBeforeTabArr.Length - 1
MsgBox(WordBeforeTabArr(d))
Next
End Sub
I wrote the above function to get all words before tab but I got all the words into array. I've been trying to use the Split method above. What is another method to split those words ? Can anyone show me some code to get this done right ?
I know this can be done with regular expression but I don't know regex yet. If you can show me how to get this done with regex it'll be awesome. Thanks.
You could try the split function on String. It could be used like this:
Dim lines() As String = IO.File.ReadAllLines(filename)
For Each line As String In lines
Dim words() As String = _
line.Split(New Char() {vbTab}, StringSplitOptions.RemoveEmptyEntries)
Next
The words array for each line would the two words. One word at each position. You could fill your two arrays or write the values out to a text file or file as you split the lines of the input file in the loop.
First of all above code is not compiling: See proper code as follows:
Dim lines() As String = IO.File.ReadAllLines(test_Filename)
For Each line As String In lines
Dim words() As String = _
line.Split("\t".ToCharArray()(0), StringSplitOptions.RemoveEmptyEntries)
Next