VB2010 Extract a string of numbers from a string or array - arrays

I have a filepath that I would like to pull the starting directory job number from the beginning of the filepath. Except I don't know how to just pull the number string out of the filepath string. (i.e.: filepath= Q:\2456_blah_blah\file.txt - or something) I'd like to just pull '2456' as a string,
then put that number string into TextBox2 I've created on my form.
The code I have so far spits out a '0' instead of the number string desired.
Any help would be much appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.OpenFileDialog1.FileName = Nothing
If Me.OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = Me.OpenFileDialog1.FileName
End If
If GetInfo() = True Then
For Each Xitem In ExcelRowList
Dim lvitem As ListViewItem
lvitem = Me.ListView1.Items.Add(Xitem.C1)
Next
End If
'''Here is where I call the GetFilePathOnly function
TextBox2.Text = GetFilePathOnly(TextBox1.Text)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
'''Section below is what defines my number string, then I call it above for the Button1.Click operation(towards the end)
Private Function GetFilePathOnly(ByVal Fullpath As String) As String
Dim File As String = Fullpath
Dim number As Double = Val(File)
Dim outcome As String = number.ToString 'File.Substring(0, File.LastIndexOf("\") + 1)
Return outcome
End Function
Thanks

You could also use a regular expression easily.
Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("Q:\2456_blah_blah\file.txt").Value

A lazy way would be to use Split:
TextBox2.Text = path.Split("\")(1).Split("_")(0)

Related

Moving file contents into an array

Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)

VB.net get item value in string array

This is my code :
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim JsonSub As String = "{""subdomain01"":[""21"",""subdomain01"",""4""],""subdomain02"":[""22"",""subdomain02"",""4""]}"
Dim objSub As JObject = JObject.Parse(JsonSub)
Dim dataSub As List(Of JToken) = objSub.Children().ToList
For Each subdomain As JProperty In dataSub
subdomain.CreateReader()
For Each pSub As JObject In subdomain.Value.ToString
MsgBox(pSub.ToString)
Next
Next
End Sub
How can I get value in array of that string :
[""21"",""subdomain01"",""4""]
If you want to get just that, do a split:
Dim resultarray As String() = JsonSub.Split(":")(1).Split(",")
Dim result As String = resultarray(0) & "," & resultarray(1) & "," & resultarray(2)
as JsonSub.Split(CChar(":"))(1) will return [""21"",""subdomain01"",""4""],""subdomain02""
and in turn, split that with the comma will net you 4 substring between those ",". You only need to take the first 3, and the result is as shown.

Display value of selected array

I have a CSV file that is formatted as (name,number) on each line.
I'm creating an app that loads all names, index(0), into a listbox at form-load and when a name is selected the number, index(1), is displayed in a .textbox.
I start by filling an array and displaying index(0) in the box. No Prob. But when the selected text changes I have problems. If you cant tell I'm new to VB. If I could assign a var to the selected text I could use a while loop but I'm not sure how to assign that. Is there a better way to go about this? Below is my source. Any help would be great.
Public Class Form1
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim myData = line.Split(","c)
Dim mName = myData(0)
Dim mPhone = myData(1)
ListBox1.Items.Add(mName)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim query = line.Split(","c)
Dim mName = query(0)
Dim mPhone = query(1)
TextBox2.Text = mPhone
Next
End Sub

VB.NET CreateInstance of structure

I wrote the following code:
Public Class Form1
Private Structure udtThing
Dim SomeText As String
Dim SomeElements() As String
Public Shared Function CreateInstance() As udtThing
Dim result As New udtThing
result.SomeText = String.Empty
ReDim result.SomeElements(2)
result.SomeElements(0) = String.Empty
result.SomeElements(1) = String.Empty
result.SomeElements(2) = String.Empty
Return result
End Function
End Structure
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings() As udtThing
nThings = Array.CreateInstance(GetType(udtThing), 10)
End Sub
End Class
I partly works, nThings becomes an array of 11 udtThings.
But .SomeElements is not redimmed to 3 strings of String.Empty, but it is "Nothing" instead.
Does anybody see where I went wrong?
Thank you very much!
By design, a Redim is required. Array.CreateInstance() isn't going to perform that operation, it can't guess what size is required. You'll have to help:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim nThings(10) As udtThing
For ix As Integer = 0 To UBound(nThings)
nThings(ix) = udtThing.CreateInstance()
Next
End Sub

Null Reference Exception - Read from CSV

I have to code a WPF application for college which reads from a csv file. I get a null reference exception when I want to output the parts of the CSV lines into arrays. You can find the line where the error happens in commentary. Here is the code.
Imports System.Windows.Forms
Imports System.IO
Imports System.Globalization
Class MainWindow
Private foldername As String
Private arrGemeenten As String()
Private arrOppervlakte As Double()
Private arrInwoners As Integer()
Private arrDeelgemeenten As Integer()
Private Sub cboProvincie_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cboProvincie.SelectionChanged
CSVInlezen()
End Sub
Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
FileBrowserAanmaken()
comboBoxVullen()
End Sub
Private Sub comboBoxVullen()
For Each file As String In IO.Directory.GetFiles(foldername)
If file.EndsWith(".csv") Then
Dim filenaam As String = System.IO.Path.GetFileNameWithoutExtension(file)
cboProvincie.Items.Add(filenaam)
End If
Next
End Sub
Private Sub FileBrowserAanmaken()
'folderbrowserdialog aanmaken
Dim fbd As New FolderBrowserDialog
fbd.SelectedPath = AppDomain.CurrentDomain.BaseDirectory
' Show the FolderBrowserDialog.
Dim result As DialogResult = fbd.ShowDialog()
If (result = Forms.DialogResult.OK) Then
foldername = fbd.SelectedPath
End If
End Sub
Private Sub CSVInlezen()
Dim filepath As String = foldername & "\" & cboProvincie.SelectedValue & ".csv"
If File.Exists(filepath) Then
fileInlezenHulpMethode(filepath)
End If
End Sub
Private Sub fileInlezenHulpMethode(ByVal path As String)
'declarations
Dim sr As New StreamReader(path)
Dim iTeller As Integer = 0
Dim arrLijn As String()
Dim culture As New System.Globalization.CultureInfo("nl-BE")
'eerste lijn meteen uitlezen, dit zijn kolomkoppen en hebben we niet nodig
'read out first line, these are titles and we don't need them
sr.ReadLine()
Do While sr.Peek <> -1
Dim lijn As String = sr.ReadLine()
arrLijn = lijn.Split(";")
arrGemeenten(iTeller) = Convert.ToString(arrLijn(0)) 'HERE I GET THE ERROR!
arrOppervlakte(iTeller) = Double.Parse(arrLijn(2), NumberStyles.AllowDecimalPoint, culture.NumberFormat)
arrInwoners(iTeller) = Integer.Parse(arrLijn(3), NumberStyles.Integer Or NumberStyles.AllowThousands, culture.NumberFormat)
arrDeelgemeenten(iTeller) = Convert.ToString(arrLijn(4))
Loop
End Sub
End Class
You haven't created the array, you have only created a reference for it. To create the array you need to specify a size, for example:
Private arrGemeenten As String(100)
However, to specify the size, you need to know the size when you create the array. (Well, actually you put all data in the first item, so just the size 1 would keep it from crashing, but I don't thing that's what you intended.) You probably want to use lists instead:
Private gemeenten As New List(Of String)()
Then you use the Add method to add items to the list:
gemeenten.Add(Convert.ToString(arrLijn(0)))
Also, consider putting the data in a single list of a custom object, instead of having several lists of loosely coupled data.

Resources