I can read all text from a text file(*.txt) using readalltext function in VB, but I want to split the text in other textboxes and one text file contains data and I want to split it, my text file is next:
x=first name
y=last name
z=age
And I want the code which can manage read data from that text file and after that split data in three textboxes like that.
textbox1.text=x
textbox2.text=y
textbox3.text=z
and last output was that
textbox1.text=first name
textbox2.text=last name
textbox3.text=age
So my problem is next: I want the code that can read x, y and z values from one text file.
Here's an example of code :
For Each line In File.ReadAllLines(file)
Select Case True
Case line.StartsWith("x=")
TextBox1.Text = line.Split("=")(1)
Case line.StartsWith("y=")
TextBox2.Text = line.Split("=")(1)
Case line.StartsWith("z=")
TextBox3.Text = line.Split("=")(1)
End Select
Next
Consider loading the contents into a List(Of String()):
Dim lst = File.ReadAllLines("filename.txt").Select(Function(line) line.Split("=")).ToList
Then if you store your textboxes in a List(Of TextBox), you could fill the corresponding textboxes appropriately:
For i = 0 To lst.Count
textboxes(i).Text = lst(i)(1)
Next
Related
I'm using the VB.net forms application for this project.
so I have a text file like this
7,John,Kimberlake,john#mail.com,27,Bachelor
8,Tiny,Down,tiny#mail.com,34,Master
9,Jeniffer,Kime,Jen#mail.com,22,None
I have 1 textbox and 1 button.
The purpose is that you need to fill an id number to find the data about the person.
Dim Findstring = IO.File.ReadAllText("data.txt")
Dim Data As String = TextBox1.Text
Dim aryTextFile() As String
aryTextFile = Findstring.Split(",")
If aryTextFile.Contains(Data) Then
End If
I tried this and something like finding the index number in the array of the requested id but it didn't work.
Instead of ReadAllText use ReadLines and loop each line to get the data.
Walk through below code and comments.
There are much better ways to do this, But the below is very basic way of doing for easy understanding.
'READ EACH LINE OF THE TEXT FILE.
For Each item As String In IO.File.ReadLines("C:\\Desktop\\test.txt") 'ENSURE VALID PATH HERE
'THIS IS EACH LINE.
Dim Findstring = item
'ASSUME THIS IS TEXT ID FROM TEXT BOX.
Dim ID As String = "8"
'SPLIT THE LINE BASED ON ","
Dim aryTextLine() As String
aryTextLine = Findstring.Split(",")
'NOW YOU HAVE ARRAY TO READ EACH ITEM.
If aryTextLine(0) = ID Then
Dim name = aryTextLine(1)
End If
Next
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.
I have a line of text A;B;C;D; in a text file. what I'm wanting to achive is to populate a combobox so that it reads as follows
A
B
C
D
Using the ; char as a way to define a new combobox entry.
its supose to work in combination with the following code...
For Each line As String In IO.File.ReadAllLines("C:\TEST.txt")
If line.StartsWith("+dep+") Then
ComboBox1.Text = line.Substring(5)
End If
which selects a tag from a file with alsorts of stored data (in this case the +dep+ tag and usses this to populate the combobox)...
dose anyboy know how?
I'm ussing vb.net
So you want to take the text after <dep> and split it by ;? Then poulate a combobox with all parts:
Dim lineParts = From line In File.ReadLines(path)
Let depIndex = line.IndexOf("<dep>")
Where depIndex >= 0
Select line.Substring(depIndex + 5).Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
Dim allParts = lineParts.SelectMany(Function(p) p)
Dim bs = new BindingSource()
bs.DataSource = allParts
ComboBox1.DataSource = bs
If you want unique items only you just have to add Distinct:
Dim allParts = lineParts.SelectMany(Function(p) p).Distinct()
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)
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'