How to display a structure's instance as a string vb.net? - vb.net

My goal is be able to print out a Structure as a receipt without using a SortedList.
Structure:
Private Structure Facture
Dim noClient As String
Dim nom As String
Dim prenom As String
Dim adresse As String
Dim ville As String
Dim province As String
Dim codePostal As String
Dim courriel As String
Dim noTel As String
Dim noProduit As String
Dim marque As String
Dim modele As String
Dim annee As String
Dim couleur As String
Dim categorie As String
Dim noSerie As String
Dim prix As String
Dim dateVente As String
End Structure
Structure Instance :
Private Function getFacture(ByVal ID As Integer) As Facture
Dim receipt As Facture
receipt.noClient = mtxtNoClient.Text
receipt.nom = txtNom.Text
receipt.prenom = txtPrenom.Text
receipt.adresse = txtAdresse.Text
receipt.ville = txtVille.Text
receipt.province = CboProvince.Text
receipt.codePostal = mtxtCodePostal.Text
receipt.courriel = txtCourriel.Text
receipt.noTel = mtxtNoTel.Text
receipt.noProduit = mtxtNoProduit.Text
receipt.marque = txtMarque.Text
receipt.modele = txtModele.Text
receipt.annee = mtxtAnnee.Text
receipt.couleur = txtCouleur.Text
receipt.categorie = txtCategorie.Text
receipt.noSerie = txtNoSerie.Text
receipt.prix = mtxtPrix.Text
receipt.dateVente = dtpickerDateVente.Text
Return (receipt)
End Function
And I need to print this along side an Array of Strings.
FORMAT :
Private Sub btnAfficherVente_Click(sender As Object, e As EventArgs) Handles btnAfficherVente.Click
' gotta read each line and print them as toString formatted for facturation
Dim infoProduit As String() = New String() {"No de client:", "Nom:", "Prénom:", "Adresse:", "Ville:", "Province:", "Code Postal:", "Courriel:", "Téléphone:",
"No de produit:", "Marque:", "Modèle:", "Année:", "Couleur:", "Catégorie:", "No de série:", "Prix:", "Date de vente:"}
'Output in facturation formatted text
Dim i As Integer = 0
Do While i < infoProduit.Length
If i = 9 Then
txtFacturation.Text += vbCrLf + "==============================================" + vbCrLf
End If
txtFacturation.Text += String.Format("{0, -20}", infoProduit(i)) & vbTab & getFacture(i).ToString & vbCrLf
i += 1
Loop
End Sub
OUTPUT :
I have looked at the documentation and multiple questions on StackOverflow. Most of the answers are in regards of using a Dictionnary, Collection or SortedList.
In the documentation, the only thing I found was to Override the ToString() in the Structure, which would no work for me because that would mean I have to individually format them in ToString but that would mess the final output since I have to print it along side an Array of Strings.

I would use a class instead of a structure. But you'll need a method inside the structure that will return the wanted text.
Private Structure Facture
Dim noClient As String
Dim nom As String
Dim prenom As String
Dim adresse As String
Dim ville As String
Dim province As String
Dim codePostal As String
Dim courriel As String
Dim noTel As String
Dim noProduit As String
Dim marque As String
Dim modele As String
Dim annee As String
Dim couleur As String
Dim categorie As String
Dim noSerie As String
Dim prix As String
Dim dateVente As String
Function obtenirFactureTexte() As String
Dim resultat As String = ""
resultat &= "No de client: " & noClient & vbCrLf
resultat &= "Nom: " & nom & vbCrLf
resultat &= "Prénom: " & prenom & vbCrLf
' ...
Return resultat
End Function
End Structure
Sub Main()
Dim nouvelleFacture As New Facture
nouvelleFacture.noClient = "123"
nouvelleFacture.nom = "Lagare"
nouvelleFacture.prenom = "Bob"
Console.Write(nouvelleFacture.obtenirFactureTexte())
End Sub
You can then use that method to output the result anywhere.
txtFacturation.Text = getFacture(i).obtenirFactureTexte()

Related

Receive object reference error when iterate the xdocument to retrieve xml element value

Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
If Not lobXnode Is Nothing Then
Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
Select Nam
Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")
End If
Next
When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Looking for a way to populate listview from String array

I have a problem populating a ListView with an I have created. All of the data goes to one column instead of rows. Could you help me to populate it correctly?
Dim finalas() As String = arrf.ToArray(GetType(System.String))
For Each element As String In finalas
Dim item As New ListViewItem(element)
ListView1.Items.Add(item)
Next
I have found a solution myself, if some one needs it, here you go:
Sub readTextFile()
' Create new StreamReader instance with Using block.
Dim path As String = "D:\data.txt"
Dim st() As String = File.ReadAllLines(path) 'read the file into array of
Dim p_1 As String = ""
Dim p_2 As String = ""
Dim arrl As Integer = 11
For Each itm As String In st 'loop the array of string item by item
Dim Arr() As String = itm.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'split the string
Dim name() As String = itm.Split(New String() {"'"}, StringSplitOptions.RemoveEmptyEntries)
' Arr.Skip(1).ToArray -nenuskaito pirmojo
' Arr = Arr.Take(Arr.Length - 1).ToArray - nenuskaito paskutinio
'galutinis array
p_1 = Arr(1)
p_2 = Arr(2)
Dim finarr As New List(Of String)
finarr.Add(p_1)
finarr.Add(p_2)
finarr.Add(name(1))
For i As Integer = 4 To arrl
finarr.Add(Arr(((Arr.Length - 1) - arrl) + i))
Next
'MsgBox(finarr(0) & finarr(1) & finarr(2) & finarr(3) & finarr(4) & finarr(5) & finarr(6) & finarr(7) & finarr(8) & finarr(9) & finarr(10))
Dim items As New List(Of ListViewItem)
Dim lvItem = New ListViewItem(finarr(0))
For i = 1 To 10
lvItem.SubItems.Add(finarr(i))
Next i
items.Add(lvItem)
ListView1.Items.AddRange(items.ToArray)
Next
Return
End Sub

Extracting Portion of Url using VB.net

I have this URL
https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607
I am trying to Extract 31.888433,73.263572 from the URL
and send 31.888433 to TextBox 1
and 73.263572 to TextBox 2
Can you give me an example how can i do this with regex or anything else
You can use string.split(). This method takes an array of chars which are the discriminants for the splitting. The better solution is to split by '/', take the string that starts with '#' and then split it by ','. You'll have an array with two string: first latitude, second longitude.
Should be immediate using LINQ
The explanation is in the code comments.
Dim strURL As String = "https://www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
'Find the index of the first occurance of the # character
Dim index As Integer = strURL.IndexOf("#")
'Get the string from that the next character to the end of the string
Dim firstSubstring As String = strURL.Substring(index + 1)
'Get a Char array of the separators
Dim separators As Char() = {CChar(",")}
'Split the string into an array based on the separator; the separator is not part of the array
Dim strArray As String() = firstSubstring.Split(separators)
'The first and second elements of the array is what you want
Dim strTextBox1 As String = strArray(0)
Dim strTextBox2 As String = strArray(1)
Debug.Print($"{strTextBox1} For TextBox1 and {strTextBox2} for TextBox2")
Finally Made a working Code Myself
Private _reg As Regex = New
Regex("#(-?[\d].[\d]),(-?[\d].[\d])", RegexOptions.IgnoreCase)
Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
Dim url As String = WebBrowser2.Url.AbsoluteUri.ToString()
' The input string.
Dim value As String = WebBrowser2.Url.ToString
Dim myString As String = WebBrowser2.Url.ToString
Dim regex1 = New Regex("#(-?\d+\.\d+)")
Dim regex2 = New Regex(",(-?\d+\.\d+)")
Dim match = regex1.Match(myString)
Dim match2 = regex2.Match(myString)
If match.Success Then
Dim match3 As String = match.Value.Replace("#", "")
Dim match4 As String = match2.Value.Replace(",", "")
Label1.Text = match3
Label2.Text = match4
End If
End Sub
Dim url As String = "www.google.com/maps/place/Aleem+Iqbal+SEO/#31.888433,73.263572,17z/data=!3m1!4b1!4m5!3m4!1s0x39221cb7e4154211:0x9cf2bb941cace556!8m2!3d31.888433!4d73.2657607"
Dim temp As String = Regex.Match(url, "#.*,").Value.Replace("#", "")
Dim arrTemp As String() = temp.Split(New String() {","}, StringSplitOptions.None)
Label1.Text = arrTemp(0)
Label2.Text = arrTemp(1)

Variable '' is used before it has been assigned a value.

I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.
Sub Main()
Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
Console.WriteLine("Downloading . . . ")
Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
If System.IO.File.Exists(FileDelete) = True Then
System.IO.File.Delete(FileDelete)
End If
download()
Threading.Thread.Sleep(1000)
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
Dim tempRead As String ' = s.ReadLine
Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
Dim i As Integer = 0
Dim tempStore As String()
s.ReadLine()
s.ReadLine()
Do Until s.EndOfStream = True
tempRead = s.ReadLine
tempSplit = tempRead.Split(New Char() {" "})
Console.WriteLine(tempSplit(0))
tempStore(i) = tempSplit(0)'The part that gives me the error
i = i + 1
Loop
Console.ReadKey()
End Sub
Sub download()
Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
'"Enter file URL"
Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
'"Enter directory"
Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
My.Computer.Network.DownloadFile(url, dirr)
'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.
Function countlines()
Dim count As Integer
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
s.ReadLine()
s.ReadLine()
count = 0
Do Until s.EndOfStream = True
s.ReadLine()
count = count + 1
Loop
Console.WriteLine(count)
Return count
Console.ReadKey()
End Function
Then what you do is:
Dim count As Integer
count = countlines()
Dim tempStore(count) As String

convert double quote string to string array in vb.net

How can I convert below string,
"[""1"",""2"",""3""]"
To this,
["1","2","3"]
I have try this without success:
Replace(string, """", "")
In vb.net - you should try like this,
Dim stringVar As String = "[""1"",""2"",""3""]"
stringVar.Replace("""", "")
Also check this to use Replace function.
If I understood correctly you can try something like this :
Dim s As String = "[""1"",""2"",""3""]"
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(s, "\d+")
Dim svals As String = ""
For Each m As System.Text.RegularExpressions.Match In collection
If svals = String.Empty Then
svals = m.Value
Else
svals = svals & "," & m.Value
End If
Next
Dim rr() As String
rr = svals.Split(",") ' Result as array of string
Demo