Visual Basic Loop and Display one line at a time - vb.net

I'm using visual studios 2008, VB9 and I am trying to write an app that basically performs calculations on a set of data input by a user. During the calculations, I want to display the data at each step, and have it retained in the display area on the GUI (not overwritten by the next data being displayed).
For example:
UserInput = 1
Do
UserInput += 1
OutputLabel.Text = "UserInput " & UserInput
Loop Until UserInput = 5
and the output would look like
UserInput 1
UserInput 2
UserInput 3
UserInput 4
UserInput 5
I tried this, and other loop structures and can't seem to get things right. The actual app is a bit more sophisticated, but the example serves well for logical purposes.
Any tips are welcome, thanks!

This is the simple version:
Dim delimiter as String = ""
For UserInput As Integer = 1 To 5
OutputLabel.Text &= String.Format("{0}UserInput {1}", delimiter, UserInput)
delimiter = " "
Next
However, there are two problems with it and others like it (including every other answer given so far):
It creates a lot of extra strings
Since it's in a loop the label won't be able to process any paint events to update itself until you finish all of your processing.
So you may as well just do this:
Dim sb As New StringBuilder()
Dim delimiter As String = ""
For UserInput As Integer = 1 To 5
sb.AppendFormat("{0}UserInput {1}", delimiter, UserInput)
delimiter = " "
Next
OutputLabel.Text = sb.ToString()
And if you really want to have fun you can just do something like this (no loop required!):
OutputLabel.Text = Enumerable.Range(1, 5).Aggregate(Of String)("", Function(s, i) s & String.Format("UserInput {0} ", i))

You need to concatenate the value in OutputLabel.Text.
OutputLabel.Text &= "UserInput " & UserInput
You might also want to reset it before the loop: OutputLabel.Text = ""

If you need an iterated index you can try something like the following
For I As Integer = 1 To 5
If I > 1 Then OutputLabel.Text &= " "
OutputLabel.Text &= "UserInput " & I.ToString()
End For
If you have user inputs in a collection, you might better be served by using ForEach loop.

Do you need to do it in a GUI? If it is simply processing and putting out rows like that, maybe you should consider a console application, in which case it becomes REALLY easy, in simply calling
Console.WriteLine("my string")

All of these ways actually work really well but the one that fit my situation the best was this:
Do
Dim OutputString as String
Application.DoEvents() 'to make things paint actively
UserInput += 1
OutputString = String.Format("{0}", UserInput)
ListBox.Items.Add(OutputString)
Loop Until UserInput = 5
I changed things to a listbox but tried this same method with textboxes and labels, with some tweaks, they all worked very well. Thanks for all your help!

I'd use a more appropriate control, like richtextbox
Dim UserInput As Integer = 0
Const userDone As Integer = 5
RichTextBox1.Clear()
Do
RichTextBox1.AppendText(String.Format("User input {0:n0} ", UserInput))
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.Refresh() 'the data at each step
UserInput += 1
Loop Until UserInput = userDone

Related

How to store textbox input into a two dimensional array?

okay so i have two textboxes for user input, and i need help storing these into a single two dimensional array.
for 49 columns and two rows (states, capitals)
i already declared the array to:
Dim states(49,1) as string
states(0,0)= textbox1.text
states(0,1) = textbox2.text
im not sure what else to do because i have
am i storing this right? im not sure what more to do to store the rest of input into the array.
any help would be appreciated. thank you!
Declare module/class scope variables:
Dim states(49,1) as string
Dim nextInd as Integer = 0
Then in your button click handler:
If nextInd <= 49 Then ' Make sure you are not trying to fill values past the dimensions of the array
states(nextInd, 0) = textbox1.text
states(nextInd, 1) = textbox2.text
nextInd += 1 ' To increment the next index to use by 1
textbox1.text = ""
textbox2.text = ""
End If
And then to display the contents of the array, you need a loop:
' Use a string builder so you can modify the same string object to show it all together in the message box
Dim contents As New StringBuilder("")
For st = 0 To 49
contents.Append(states(st, 0) & ": " & states(st, 1) & Environment.NewLine)
' Or however you want To format it
Next
MessageBox.Show(Me, contents) ' MsgBox is old - use MessageBox instead

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

How do I display the result of a loop on a new line in a text box?

Basically, how do I write a new line in a text box, keeping the existing information as well.
If I have for loop,
For i As Integer = 1 To 10
Dim result = i
i = i + 1
textbox1.text = result
Next
This will display '10' in the textbox. I want it to be like:
1
2
3
4
...
First, your TextBox must allow multiple lines. This is a property of the textbox control that you can set from the designer or from the code. You may want to ensure that a scroll bar is there to scroll in case the height is not large enough.
If you want to set the properties from code, use this code in the Load event of the form.
' Set the Multiline property to true.
textBox1.Multiline = True
' Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical
' Change the height of the textbox so that it could accomodate the lines
TextBox1.Height = 120
Now, your approach had a major problem in this line:
textbox1.text = result
The way you coded it, every new value of i, would overwrite the old value. What you want to do is to first construct a string, then send the entire string to the TextBox control. This is not required had you been using Console.WriteLine method.
Method 1
Dim s as string
s=""
For i As Integer = 1 To 10
s = s & Environment.Newline & i.ToString() 'we use Environment.NewLine to force new line
Next i
textbox1.text = s
Method 2
.NET offers a class to handle strings better than the way we did before. It won't matter in your case but it is the efficient way to handle concatenation when volume is large and/or performance matters
Dim s as new System.Text.StringBuilder() 'Initialize stringbuilder instance
For i As Integer = 1 To 10
s.AppendLine (i.ToString()) 'We use stringbuilder to concat. and inser line feed
Next i
textbox1.text = s.ToString()
Note: If you want double spacing then you need to add a linefeed (using & ) to both of the above methods.
Something like this should work:
For i As Integer = 1 To 10
if i = 1 then
textbox1.text = i
else
textbox1.text &= vbcrlf & i
end if
Next
For i = 1 To 10
textbox1.AppendText(vbNewLine & i)
Next

Listbox Remove Spaces

I am trying to use this code to remove spaces from a listbox but it is not working
Dim word As String() = {" "}
For i As Integer = 0 To ListBox5.Items.Count - 1
For Each Word As String In word
If ListBox5.Items(i).ToString.Contains(Word) Then
ListBox5.Items(i) = ListBox5.Items(i).ToString.Replace(Word, String.Empty)
End If
Next
Next
any help would be appreciated a lot.
You define a string array with one value and its static, why?
It seems you could do this simply by coding it like this
scan every item and replace " " with string.empty,
don't bother checking if it exists, just run the replace statement on every item
For i As Integer = 0 To ListBox5.Items.Count - 1
ListBox5.Items(i) = ListBox5.Items(i).ToString.Replace(" ", String.Empty)
Next
try this code
For i As Integer = 0 To ListBox5.Items.Count - 1
ListBox5.Items(i) = ListBox5.Items(i).ToString.Replace(" ", Nothing)
Next
fist we have to loop through the listbox items. we declared the items from index 0 to the final item index,ie listbox.items.count-1 . this is stored in a variable i. next all the items ,say from 0 to count-1 is replaced.
istBox5.Items(i).ToString.Replace(" ", Nothing) " " indicates a space and'nothing' indicates null.you can also use regex.replace here by importing system.regularexpressions.

I want to create a dynamic variable in vb6

My code-
For i= 1 to 10
str & i = InputBox("Enter a number")
Next i
The problem is that it does not create the variable and highlights the "&" sign. Please help.
P.S. I dont want to use an array.
Edit (Updated requirement from one of the comments):
I can't use an array because its for a school project and i'm not allowed, and the user can enter as many numbers as he wants to, so..?
As Marco says, you can't have variable variables.
Sounds like you need an array instead:
dim inputs(1 To 10) as Integer
For i= 1 to 10
inputs(i) = InputBox("Enter a number")
Next i
UPDATE: Answering requirements of unknown number of inputs, and absence of arrays:
You can possibly use a collection, as this will take new inputs as you require:
'Create a collection and a temp variable
Dim strs As New Collection
Dim str As String
'Loop until the input is empty
Do
str = InputBox("Enter a number")
If str <> "" Then strs.Add (str)
Loop Until str = ""
'Then later you can do
Dim val As String
For Each val In strs
'Do something with val
Next
You say the user can enter as many numbers as they want. Maybe you don't want a For loop then, rather a Do or While loop that you Exit when the user is done (when they leave the input box blank or type "done" or something).
But also, you probably don't need to store all the numbers at once. Just input the number into a single variable, do whatever processing you need to do with it inside the loop body (e.g., add it to a total), and then reuse the same variable name on the next iteration of the loop.
If you really need to store them all at once, yes, you'd need an array (or a Dictionary or Collection object, but still, they're like arrays).
I want to create a dynamic variable in VB6
This is what you think you want, but it certainly is not what you need.
You might use an array for this:
Dim str(10) As String
Dim i As Integer
For i= 1 to UBound(str)
str(i) = InputBox("Enter a number")
Next i
If there is no upper limit, you could use a collection.
Dim str As New Collection
Do
str.Add InputBox("Enter a number"), CStr(str.Count)
Loop Until str(str.Count) = ""
str.Remove str.Count
I think what the poster is trying to do has been misread. They want to use a single variable but continue to update it with additional user input. A VB string will work nicely for this and appending a vbCrLf would make splitting the string to separate the value easy. This is very similar to Tomalak's sample.
Dim strUserInput As String
Do
strUserInput = InputBox("Enter a number")
Text1.Text = Text1.Text & vbCrLf & strUserInput 'I am displaying the user input but another string can be used here also
Loop While Len(strUserInput) > 0