Search field in text file - vb.net

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'

Related

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

Prevent Character Count Going Up By 2 On vbNewLine

I'm having a problem with the character count in a textbox.
If e.KeyChar = ChrW(13) Then tsCount.Text = "Character Count: " & tbText.Text.Count - 2
Basically I want to prevent the character count going up by 2 when the user creates a new line in the textbox. I've tried that code above, but didnt really work.
Also, in my program the user cannot create a new line without having any text in the textbox by using
the code below:
If tbText.Text = String.Empty And e.KeyChar = ChrW(13) Then e.Handled = True
tsCount is a label, and tbText is my textbox. Is it possible to prevent it by going up by 2?
You can remove all new line characters by using String.Replace(String, String) before performing the measurement of length.
Dim newText As String = tbText.Text.Replace(vbNewLine, String.Empty)
tsCount.Text = newText.Count

Search for keywords send preceeding text to specific textboxes vb.net

I have a txt text file in that I have a few lines as follows:
SW1:bla bla bla
SW2:yada yada yada
SW3:yak yak yak
I would like vb net to look for the line SW1: and place whatever preceeds in textbox1
like wise sw2: in textbox2, and SW3: in textbox 3:
all the remaining lines go in rich textbox1
is it possible to search for key words and send the preceeding text to specific textboxes ussing vb.net?
You can usee File.ReadAllLines to load the entire file into an array of strings (one item per line in the file). Then, you can use the String.StartsWith and String.SubString methods to parse each line, for instance:
For Each line As String In File.ReadAllLines(filePath)
If line.StartsWith("SW1:") Then
TextBox1.Text = line.SubString(4)
End If
'...
Next
Alternatively, if all the keywords are the same length, you could use a select case:
For Each line As String In File.ReadAllLines(filePath)
Select Case line.SubString(0, 4)
Case "SW1:"
TextBox1.Text = line.SubString(4)
' ...
End Select
Next
Or, if all the keywords end with a colon, and none of the values contain that character, you could use String.Split to split the key/value pair from each line:
For Each line As String In File.ReadAllLines(filePath)
Dim parts() As String = line.Split(":"c)
Select Case parts(0)
Case "SW1"
TextBox1.Text = parts(1)
' ...
End Select
Next
To read the rest of the file into a rich text box, there are multiple ways you could do that, but one of the simplest ways would be like this:
Dim builder As New StringBuilder()
For Each line As String In File.ReadAllLines(filePath)
If line.StartsWith("SW1:") Then
TextBox1.Text = line.SubString(4)
Else If line.StartsWith("SW2:") Then
TextBox2.Text = line.SubString(4)
Else If line.StartsWith("SW3:") Then
TextBox3.Text = line.SubString(4)
Else
builder.AppendLine(line)
End If
Next
RichTextBox1.Text = builder.ToString()
Since Mr. Steven already got the answer. You can also use like this,.
Dim source = File.ReadAllLines("d:\source.txt")
sw1TextBox.Text = source.Where(Function(c) c.StartsWith("SW1:")).FirstOrDefault().Substring(4)
sw2TextBox.Text = source.Where(Function(c) c.StartsWith("SW2:")).FirstOrDefault().Substring(4)
sw3TextBox.Text = source.Where(Function(c) c.StartsWith("SW3:")).FirstOrDefault().Substring(4)

How to delete a string from a RichTextBox?

I am trying to parse junk and narrow down a bunch of text. How do I delete the current line if a does not match? I would like to remove the line entirely:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
Dim a As String = RichTextBox1.Lines(i).ToString
If Not a = "SaveThisLine" Then
'delete the active line
End If
Next
Also how would I match partially? Such as if not a = "SaveThisLine" & * (to use a wildcard).
I would not touch original text and rather save valid lines into a StringBuilder, so if line is valid, AppendLine to it. In the end dump back into RichTextBox1.Text using StringBuilder.ToString.
For partial match in VB.NET you can use a native Like operator:
"aaa" Like "a*"
Returns True.
Or use regular expressions:
System.Text.RegularExpressions.Regex.Match("aaa", "^a").Success
Also returns True.
You can do it in this way to:
For i As Integer = 0 To RichTextBox1.Lines.Length - 1
If RichTextBox1.Lines(i) = "2" Then
RichTextBox1.Text = Replace(RichTextBox1.Text, RichTextBox1.Lines(i), "", , 1)
End If
Next