transfering fixed words in multiline textbox in visual basic to seperate single line textboxes - vb.net

I am having problem in visual basic textbox so my actual problem is i have a Multiline textbox1 containing FirstName="JOHN" in one line and LastName="SMITH" in the newline and i want to transfer only JOHN in separate singleline textbox2 and SMITH in other singleline textbox3.
i want this to happen on click of copy button.
The lefthanside of the textbox1 like FirstName,LastName remains constant whereas the rightside like JOHN,SMITH are changing in nature.
I have created a separate function and i have tried so far as
Public Class Form1
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
End Class
here's the link to screenshot of what i want to accomplish.
http://tinypic.com/r/2mcev5w/8
Thanks in advance

I think you could separate the text from the textbox by new lines. Something like:
Dim itemsInTextBox as String() = TextBox1.Text.Split(vbCrLf.toCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName as String = itemsInTextBox(0).Split("=".toCharArray)(1)
Dim secondName as String = itemsInTextBox(1).Split("=".toCharArray)(1)
This is assuming your lines in the textbox are separated by new lines. If it is separated by something else, just put that in the split method. This also keeps the quotation marks (do you want this?)
EDIT: for setting other textboxes
TextBox2.Text = firstName
TextBox3.Text = secondName
EDIT2: You have to create those variables on button click. If you do it globally, it will be run before your TextBox1 exists.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub

Your sample and your description are different. In your sample you use FIRSTNAME=JOHN and in your description you use first-name="john" which are very different.
Lets use your sample. Your test should look like this.
TextBox2.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
TextBox3.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
Of you try it like this, you will see it's not returning the right information.
You'll have to split each line and then split these line again with the = sign like you did.
Function GetValue(ByVal data As String, ByVal key As String) As String
Dim lines() As String = data.Split(Chr(10))
For Each line As String In lines
line = line.Trim()
Dim subData() As String = line.Split("="c)
If subData(0) = key Then
Return subData(1)
End If
Next
Return ""
End Function
Sub Main()
Dim data As String
data = "FIRSTNAME=JOHN" & Environment.NewLine & "LASTNAME=SMITH"
Console.WriteLine(GetValue(data, "FIRSTNAME"))
Console.WriteLine(GetValue(data, "LASTNAME"))
Console.ReadLine()
End Sub

Just move the declaration of the itemsList into the sub for the copy.
EDIT: Also need to move the declaration of the strings
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub

Related

How can I display a name in a different sequence using strings?

I'm having trouble with a problem that I was assigned for my Visual Basic 2012 class. The instructions are below. So far, I have it displaying only the first name entered, and nothing else. How can I make it to display both the first name and the last name in the sequence requested?
String Problem: Enter your first and last name in a text box. Take the name and display it in a label box showing the last name, first name.
Text Box Entry: Jane Doe
Label Box: Doe, Jane
The code I have so far is below. Thanks for any help!
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
firstlabel.Text = firstname
fulltextbox.Focus()
End Sub
Private Sub fulltextbox_TextChanged(sender As Object, e As EventArgs)
firstlabel.Text = String.Empty
fulltextbox.SelectAll()
End Sub
Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub
You are on the right track by first determining where the space is located:
indexnum = fullname.IndexOf(" ")
Now based on this index, you can split the string into two strings, firstname and lastname:
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
You need to use indexnum+1, instead of indexnum, otherwise you will include the spacing character.
Finally you group them together again by using the string concatenation operator (&):
firstlabel.Text = lastname & ", " & firstname
The final method thus looks like:
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String
fullname = fulltextbox.Text
indexnum = fullname.IndexOf(" ")
firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)
firstlabel.Text = lastname & ", " & firstname
fulltextbox.Focus()
End Sub
Note, this won't work if your using middle initials. Also, I would remove fulltextbox.SelectAll() from fulltextbox_TextChanged
Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim Names() As String = fulltextbox.Text.Split(" "c)
If Names.Count = 2 Then
firstlabel.Text = Names(1) + ", " + Names(0)
ElseIf Names.Count = 0 Then
MessageBox.Show("Please enter name.")
Else
MessageBox.Show("Invalid Nmae entered.")
End If
fulltextbox.Text = ""
End Sub

How to pass all value of ListBox Control to a function?

I am writing a simple application to read the value a textbox and add to a listbox control . But i have to pass the listbox control to function . Any suggestion ?
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
test("E:\Satyajit.txt")
End Sub
Public Function test(ByVal filename As String)
Dim FILE_NAME As String = filename
Dim TextLine As String
Dim result As String = Path.GetFileName(FILE_NAME)
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
words = TextLine.Split(New Char() {","c})
ListBox1.Items.Add(words(3) & "," & words(4))
objItem = ListView1.Items.Add(words(3) & "," & words(4))
Loop
test1(ListBox1.Items)//pass the listbox value hare
End Function
Public Function test1(ByVal value As String)
Dim Fest As String = value
MsgBox(Fest)
End Function
You're passing the contents of a ListBox to a method that is just displaying them in a MsgBox(). There are two approaches you can do to accomplish what I think you're wanting.
You can pass ListBox.Items to the method and iterate through each item concatenating them into a single String or StringBuilder, then pass the String to the MsgBox(). This approach makes your method dependent on ListBoxItems.
You can iterate through ListBox.Items concatenating them into a single String or StringBuilder, then pass the String to your method. This makes your method a little more scalable.
I recommend approach #2, something like:
Dim MyListBox As New ListBox
MyListBox.Items.Add("Item1")
MyListBox.Items.Add("Item2")
MyListBox.Items.Add("Item3")
MyListBox.Items.Add("Item4")
MyListBox.Items.Add("Item5")
Dim sb As New StringBuilder
For Each Item In MyListBox.Items
sb.AppendLine(Item)
Next
Test1(sb.ToString())
The Test1 method would look like:
Public Sub Test1(ByVal value As String)
MsgBox(value)
End Sub
Results:
You could pass the whole control to the function:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox) & " characters")
End Sub
Function Length(ByVal ctrl As ListBox) As Integer
Dim TotalNumberOfItems As Integer = 0
For Each item As String In ctrl.Items.ToString
TotalNumberOfItems += 1
Next
Return TotalNumberOfItems
End Function
or just its items
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lstbox As New ListBox
lstbox.Items.Add("Hello")
lstbox.Items.Add("Second Item")
lstbox.Items.Add("Third Item")
MsgBox("The list contains: " & Length(lstbox.Items) & " characters")
End Sub
Function Length(ByVal col As ListBox.ObjectCollection) As Integer
Dim TotalNumberOfCharacters As Integer = 0
For Each item As String In col
TotalNumberOfCharacters += item.Length
Next
Return TotalNumberOfCharacters
End Function

add instance of class to listbox from .txt visual basic

New at visual basic. I'm trying to read from a csv file, split it, then take values only at index(0) and add them all to a listbox. Here's what I got. Any advice I'd appreciate.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim data() As String
Dim initFileContents() As String = IO.File.ReadAllLines("MembershipPhone.txt")
data = initFileContents.First.Split(","c)
name = data(0)
phone = data(1)
ListBox1.Items.Add(name)
TextBox1.Text = name
TextBox2.Text = phone
End Sub
Of course this only adds the first instance. I need C++ equivalent to "for each line in data.."
Just use a For loop to iterate over the lines returned by ReadAllLines():
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim data() As String
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
data = line.Split(","c)
Name = data(0)
phone = data(1)
ListBox1.Items.Add(Name)
TextBox1.Text = Name
TextBox2.Text = phone
Next
End Sub

order by date in txt file using vb.net

i made a program that takes release date and title from IMDB api and saves them in them in .txt file...can i order them by date somehow
Imports System.IO
Imports System.Xml.Linq
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim _reg As Regex = New Regex("http://www.imdb.com/title/([A-Za-z0-9\-]+)/*?", _
RegexOptions.IgnoreCase)
Dim value As String = TextBox1.Text
Dim m As Match = _reg.Match(value)
If (m.Success) Then
Dim key As String = m.Groups(1).Value
Dim url As String = "http://mymovieapi.com/?id=" + key + "&type=xml&plot=none&episode=0&lang=en-US&aka=simple&release=simple&business=0&tech=0"
Dim Document As XDocument = XDocument.Load(url)
Dim title = Document.Root.Element("title").Value()
Dim releaseDate = Date.ParseExact(Document.Root.Element("release_date").Value,
"yyyyMMdd", System.Globalization.CultureInfo.InstalledUICulture)
TextBox2.Text = "Release Date: " & releaseDate & " / Title: " & title
Else : TextBox2.Text = "Please use IMDB links"
End If
Button2.Enabled = True
End Sub
Private Sub Button2_Click_1(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter("C:\Users\Azer\Documents\Movies.txt", True)
Writer.Write(TextBox2.Text & vbCrLf)
Writer.Close()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim Reader As System.IO.StreamReader
Reader = New System.IO.StreamReader("C:\Users\Azer\Documents\Movies.txt")
Dim tempstring As String
Do
tempstring = Reader.ReadLine()
TextBox3.Text = TextBox3.Text + tempstring + vbCrLf
Loop Until tempstring = ""
Reader.Close()
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
TextBox3.Clear()
End Sub
End Class
As David said, a database would make this a lot easier. However, if you can't use a database (or have some other reason for doing it this way), here's one way to approach it.
Make a small class that holds the information (to make it easier to sort, like this:
Public Class MovieInfo
Public Property As DateTime
Public Title As String
End Class
Next, read the current file (if it exists) and populate a List<MovieInfo> with the data in it.
Dim movies As String() = File.ReadAllLines("C:\Users\Azer\Documents\Movies.txt")
Dim movieParts = From m in movies
Select m.Split(New String() { "/", ":" }, StringSplitOptions.RemoveEmptyEntries)
Dim parsedDate As DateTime
Dim movieData As List(Of MovieInfo) = (From mi In movieParts
Select New MovieInfo With
{
.ReleaseDate = _
If(DateTime.TryParseExact(mi(1).Trim, "dd.MM.yyyy", _
System.Globalization.CultureInfo.InvariantCulture, _
System.Globalization.DateTimStyle.None, _
parsedDate), parsedDate, DateTime.MinValue),
.Title = mi(3).Trim()
}.ToList()
Essentially the code above reads the text file into an array (one line per element), and then using LINQ splits each line into 4 parts based on : and /. Then it takes the result of that query and builds a List of MovieInfo, with the date string converted to DateTime for easy sorting.
The DateTime.TryParseExact takes an input string of the specified format (in this case, dd.MM.yyyy) and if possible converts it to a DateTime object. If it's successful, it returns true and the DateTime value is in the parsedDate variable. If it's not true, I use the MinValue for DateTime for the ReleaseDate property of the MovieInfo class.
After that, you'll get the new data from your API call and add it to the List of MovieInfo (you'll probably want to eliminate any duplicates). Since you didn't post the format of the data from the API, it's rather hard for me to give you a code sample to parse it, but in a nutshell you can build a second list of MovieInfo objects and then merge the existing and new list together.
Then you sort the List of MovieInfo and overwrite the original text file. Something like this should do the trick:
movieData.Sort(Function(x, y) y.ReleaseDate.CompareTo(x.ReleaseDate))
Dim output As New StringBuilder()
For Each info As MovieInfo in movieData
output.Append("Release Date: ")
output.Append(info.ReleaseDate.ToString("dd.MM.yyyy"))
output.Append(" / Title: ")
output.Append(info.Title)
output.Append(Enviroment.NewLine)
Next
File.WriteAllText("C:\Users\Azer\Documents\Movies.txt", output.ToString())
This code sorts the list with a lambda expression to put the movies in date order (newest to oldest). It then uses a StringBuilder with a For Each loop to build the output, and then writes it to the file (overwriting the file if it already exists).
Note that if you reverse the x and the y in the Sort, you'll get oldest to newest by date.
Dim allLines As String() = File.ReadAllLines("your file name")
System.Array.Sort(allLines)
IO.File.WriteAllLines("your file name", allLines) 'assuming you want to write the file

How to read a specific line from a text file in VB

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
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
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.