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

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

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.

A way to change font color besides *.SelectionColor, or a way to better make use of it?

So, I'm trying to create a function or two that takes html tags and colors them differently than the rest of the text (similar to how Visual Studio does it for key words like Dim). The only way I have found, is to use a rich text box and then do *.SelectionColor = Color.Blue, or something similar. Is there any other way to do this? I made it so whenever the textbox updates, it reads through it at changes all html tags to a different color. This works fine with a really short html file, but when they get to be larger, it takes too long, and the selection moves the cursor around.
So, is there any other way to do this, even if I have to use something other than a rich text box? If not, does anyone see a way to improve this?
Here are the two functions that run when the textbox updates. Tag is blue, attributes are red, stuff in quotes is green.
'//////////////////////////////////////////////////////////////////////////
'// findTag()
'// -finds a tag
'//////////////////////////////////////////////////////////////////////////
Private Function findTag()
Dim tag As String = ""
Dim i As Integer = 0
Dim startTag As Integer
While (i < txtCurrentFile.TextLength - 1)
If txtCurrentFile.Text(i) = "<" Then
startTag = i
While txtCurrentFile.Text(i) <> ">"
tag += txtCurrentFile.Text(i)
i += 1
End While
tag += ">"
colorCode(startTag, tag)
tag = ""
End If
i += 1
End While
Return Nothing
End Function
'//////////////////////////////////////////////////////////////////////////
'// colorCode()
'// -colors different tags accordingly
'//////////////////////////////////////////////////////////////////////////
Private Function colorCode(ByVal startIndex As Integer,
ByVal tag As String)
Dim i As Integer = 0
Dim isAttributes As Boolean = False
Do While (tag(i) <> " " And tag(i) <> ">")
txtCurrentFile.Select(startIndex + i, 1)
txtCurrentFile.SelectionColor = Color.Blue
i += 1
Loop
If i < tag.Length Then
Do Until (tag(i) = ">")
Do Until (tag(i) = Chr(34))
txtCurrentFile.Select(startIndex + i, 1)
txtCurrentFile.SelectionColor = Color.Red
i += 1
Loop
i += 1
Do Until (tag(i) = Chr(34))
txtCurrentFile.Select(startIndex + i, 1)
txtCurrentFile.SelectionColor = Color.Purple
i += 1
Loop
i += 1
Loop
txtCurrentFile.Select(startIndex + i, 1)
txtCurrentFile.SelectionColor = Color.Blue
End If
Return Nothing
End Function
a few suggestions:
Ditch the character scanner. Replace it with anything that is speedier (RegEx, HTML Agility Pack, ...)
If you really want to keep the character scanner, then limit the scan to the area around the modifications (say, 200 characters behind and in front of the cursor)
Remember where the cursor is before you start the color process and restore it when finished.
Implement a background colorizer that does a full file re-color on a separate thread (you'll have to clone the RTB and only apply the changes if the user hasn't made any changes while the colorizer was running).
... I don't know if this would work AT ALL!!!, but it could be cool if it did...
Maybe open the file in a webbrowser control and set your coloring rules in a css sheet??
Again, I don't know if this is a good idea or not, but it might do the trick very nicely since it's already HTML you're dealing with...

Is possible to ignore the TextBox?

I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.

Search field in text file

I have some coding which displays a label if the value of a textbox matches any of the first values of each line in a textfile.
Dim sList As New List(Of String)(IO.File.ReadAllLines("Path"))
Dim i As Integer
For i = 0 To sList.Count - 1
If sList(i).StartsWith(textbox1.Text) Then
Label1.Visible = True
Exit For
Else
Label1.Visible = False
End If
Next
The problem is if the textbox has 1 and the textfile has 11 it will display the label, what would be the best way around this?
I have tried sList(i).Contains etc but none of them are doing the job.
I have tried all the suggestions here and nothing works, my textfile has numbers like the following
11
15
18
and for example if i have the number 1 in the textbox then the label is visible.
Try this:
Label1.Visible = IO.File.ReadAllLines("Path.txt").Any(Function(f) f = TextBox1.Text)
I think LINQ can be used here:
Dim text = textbox1.Text
Dim textWithSpace = String.Format("{0} ", text)
Label1.Visible = IO.File.ReadAllLines("Path").Any(Function(line) line.StartsWith(textWithSpace) OrElse line = text)
You need import System.Linq to make it work.
I assumed that space ends each word in the file.
If you want the Label to be visible when at least one of the lines starts with the text in the TextBox, you can use LINQ and Enumerable.Any:
Dim matchingLines = From l In IO.File.ReadLines("Path")
Where l.StartsWith(textbox1.Text)
Label1.Visible = matchingLines.Any()
Try changing the following line, assuming you are reading from a text file and looking for an exact match of the whole line you could try this:
If sList(i).StartsWith(textbox1.Text + Environment.NewLine) Then
That should check to make sure its the only thing on that line as it is now looking for a new line and will not match '11'