Separating lines to textbox (vb 2008) [closed] - vb.net

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to set like this
In first textbox I want 1st line
in second textbox I want 2nd line
and so one...
prezime.Text = "Vukmirovic" 'I want this to show in textbox
ime.Text = ""
jmbg.Text = ""
pol.Text = ""
daniz.Text = ""
meseciz.Text = ""
godinaiz.Text = ""
danr.Text = ""
mesecr.Text = ""
godinar.Text = ""
danvd.Text = ""
mesecvd.Text = ""
godinavd.Text = ""
regbr.Text = ""
brojtel.Text = ""
adresa.Text = ""
grad.Text = ""
opstina.Text = "" <code>
OK , i writed down the code so that Prezime: is replaced with nothing. I imported
System.Text.RegularExpressions
Now i just have to set that first line is set for prezime.text , second for ime.text and so one , help :)
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text, "Prezime: ", "")

Assuming you are using .NET
'...
Dim i As Integer = 0
Dim myFile As String = "C:\Temp\infile.txt"
'it would be good to add a try/catch here in case you get an io error
Dim lines() As String = System.IO.File.ReadAllLines(myFile)
prezime.Text = splitter(lines(i))
ime.Text = splitter(lines(++i))
'do the same for other text boxes
'you need to code the lines in the same order as input file values
lastRow.Text = splitter(lines(++i))
'...
Private Shared Function splitter(ByVal parmLine As String) As String
'split the passed string into 2 srings using the : as a separator
Dim words() As String = parmLine.Split(":")
'test to see you have 2 words returned. If not, error
If (words.Length < 2) Then
Return "Error reading from file - Expected 2 tokens spearated by : but found 1"
End If
'you don't care about the first word it is the field name. Return the 2nd
Return words(1).Trim
End Function

Assuming you're using a textbox to hold your file's content.
Public Function whichtxt(ByVal line As Integer) As TextBox
If line = 0 Then
Return TextBox2
ElseIf line = 1 Then
Return TextBox3
'And so on...
Else
Return Nothing
End If
End Function
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To TextBox1.Lines.Length - 1
Dim s As String = TextBox1.Lines(i)
whichtxt(i).Text = s
Next

First we'll write a function to parse the actual part of the input we want from each line:
Private Function GetDataFromLine(line As String) As String
'Find everything before and including ': ' and remove it
Return Regex.Replace(line, ".*: ", String.Empty)
End Function
Note: Calling the static regex methods versus creating a regex instance has some performance loss, see this answer for more details.
Then we'll read all the lines from the file and put them in the appropriate fields:
Dim lines = File.ReadAllLines("myfile.txt")
prezime.Text = GetDataFromLine(lines(0))
ime.Text = GetDataFromLine(lines(1))
jmbg.Text = GetDataFromLine(lines(2))
'...
Another possible way to solve this, would be to map your input data into a dictionary that would look like this:
"Prezime" => "Vukmirovic"
"Ime" => "Nemanja"
...
and then do something like:
prezime.Text = inputDictionary("Prezime")
You'd have to write a function that'd map the input file to a dictionary.

Related

Load textfile containing names to a textbox

I am attempting to load a text file that contains a list of names into a text box using a button on the form. Also, I would like to display the following name after the button is pressed. I have been trying to successfully implement this code for several days however, my program loads all names at once. Would anyone be able to provide advice about loading text files?
Below is a copy of my code:
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
For Each i As String In lines
Dim fullNames = lines.Where(Function(line) line.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) line.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
Next
There's no loop. Load the names into an array, initialise an index variable to 0 and load the name at that index. Each time you click the Button, increment the index and load the name at that index. Once you reach the end, you can either wrap to the beginning or tell the user there are no more names. If you don't want to wrap then an even better option would be to load the names into a queue and then just dequeue on each click.
I have been able to display the names in order however I did not use a looping structure. However, the names are output multiple times in the text box after the button is clicked.
Dim i As Integer = 0
Private Sub NextAvName_Click(sender As Object, e As EventArgs) Handles nextAvName.Click
firstName.Multiline = True 'Variable contains first name.
lastName.Multiline = True 'Variable contains last name.
Dim fullName = "" 'Variable containing full name found in text file
Dim lines = IO.File.ReadAllLines("input.txt") 'loading input file located in Debug folder.
lines = lines.ToArray
Dim element As String
element = lines(i)
Dim fullNames = element.Where(Function(line) element.Contains(" "))
If fullNames.Any() Then
Dim fullNamesSplit = fullNames.Select(Function(line) element.Split(" "c))
Dim firstNames = fullNamesSplit.Select(Function(line) line(0))
Dim lastNames = fullNamesSplit.Select(Function(line) line(1))
firstName.Lines = firstNames.ToArray()
lastName.Lines = lastNames.ToArray()
fullName = String.Join(Environment.NewLine, fullNames)
Else
firstName.Text = ""
lastName.Text = ""
End If
displayInfo.Items.Add(fullName)
i = i + 1

Currently having problems with deleting/overwriting from a file

I'm currently having problems trying to delete a line from a file and replace that line with different text (overwrite the line)
The code initially starts by extracting file contents to find the
DepartmentDetails which can be used to find DepartmentBudget and subtract AmountDue and then create a new DepartmentDetails with the new budget
Once this is complete the code will add the N̳e̳w̳ DepartmentDetails which will leave the code with having the O͟l͟d͟ and the N̳e̳w̳ DepartmentDetails in the same folder.
The code should then delete the O͟l͟d͟ DepartmentDetails from the file making the N̳e̳w̳ DepartmentBudget take it's place. i.e. Overwrite the O͟l͟d͟ DepartmentDetails with the new one.
The problem is that the code does not delete the O͟l͟d͟ DepartmentBudget but adds a line space in between the O͟l͟d͟ and N̳e̳w̳ instead.
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
Dim Order() As String = File.ReadAllLines(Dir$("OrderDetails.Txt"))
Dim OrderID As String = TxtOrderID.Text
Dim AmountDue As String = TxtAmountDue.Text
Dim DeptID As String = (Trim(Mid(Order(OrderID), 5, 4)))
Dim DepartmentDetails() As String = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
Dim DepartmentBudget As String = (Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
Dim YesNo As String
Dim sw As New StreamWriter("DepartmentDetails.txt", True)
DepartmentBudget = FormattedBudget - AmountDue
DepartmentStore.DepartmentID = LSet(DeptID, 4)
DepartmentStore.DepartmentHead = LSet((Trim(Mid(DepartmentDetails(DeptID), 5, 20))), 20)
DepartmentStore.DepartmentName = LSet((Trim(Mid(DepartmentDetails(DeptID), 25, 10))), 10)
DepartmentStore.DepartmentBudget = LSet(DepartmentBudget, 9)
DeptID = UBound(DepartmentDetails)
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
sw.WriteLine(DepartmentStore.DepartmentID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & DepartmentStore.DepartmentBudget)
sw.Close()`
'***********************Having Problems Here***********************
DepartmentDetails = File.ReadAllLines(Dir$("DepartmentDetails.Txt"))
DepartmentDetails(DeptID) = ""
File.WriteAllLines("DepartmentDetails", DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MsgBox("Department has been billed. Would you like to delete the bill?", vbYesNo)
If YesNo = vbYes Then
End If
End Sub
Who decided that this text file would be formatted with fixed length fields? All this trimming and padding could be avoided with a simple comma delimited file or an xml file or a database where it really belongs.
Code is not tested. Comments and explanations in-line.
'I assume you have a class that looks something like this
'This uses automatic properties to save you having to
'type a getter, setter and backer field (the compiler adds these)
Public Class Department
Public Property DepartmentID As Integer
Public Property DepartmentHead As String
Public Property DepartmentName As String
Public Property DepartmentBudget As Decimal
End Class
Private Sub BtnBillDept_Click(sender As Object, e As EventArgs) Handles BtnBillDept.Click
Dim DepartmentStore As New Department
'Drag an OpenFileDialog from the ToolBox to your form
'It will appear in the lower portion of the design window
Dim MyFilePath As String = ""
OpenFileDialog1.Title = "Select OrderDetails.Txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim Order() As String = File.ReadAllLines(MyFilePath)
'Changed data type, you use OrderID as an index for the Order array so it must be an Integer
Dim OrderID As Integer
'TryParse will check if you have a valid interger and fill OrderID variable
If Not Integer.TryParse(TxtOrderID.Text, OrderID) Then
MessageBox.Show("Please enter a valid Order ID.")
Return
End If
'EDIT per comment by Codexer
If OrderID > Order.Length - 1 Then
MessageBox.Show("Order Number is too high")
Return
End If
Dim AmountDue As Decimal
If Decimal.TryParse(TxtAmountDue.Text, AmountDue) Then
MessageBox.Show("Please enter a valid Amount Due")
Return
End If
'I hope you realize that the first index in Order is zero
'Mid is an old VB6 method around for compatibility
'Use the .net Substring (startIndex As Integer, length As Integer)
'The indexes in the string start with zero
Dim DeptID As Integer = CInt(Order(OrderID).Substring(5, 4).Trim) '(Trim(Mid(Order(OrderID), 5, 4)))
OpenFileDialog1.Title = "Select DepartmentDetails.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyFilePath = OpenFileDialog1.FileName
End If
Dim DepartmentDetails() As String = File.ReadAllLines(MyFilePath)
Dim DepartmentBudget As Decimal = CDec(DepartmentDetails(DeptID).Substring(35, 6).Trim) '(Trim(Mid(DepartmentDetails(DeptID), 35, 6)))
'You don't need to format anything until you want to display it
'Dim FormattedBudget As String = FormatCurrency(DepartmentBudget, 2)
'A MessageBox returns a DialogResult
Dim YesNo As DialogResult
Dim sw As New StreamWriter(MyFilePath, True)
'Shorcut way to write DepartmentBudget - AmountDue
DepartmentBudget -= AmountDue
'Set the property in the class with the proper data type
DepartmentStore.DepartmentID = DeptID
'Then prepare a string for the writing to the fil
Dim PaddedID = CStr(DeptID).PadLeft(4)
'The .net replacement for LSet is .PadLeft
DepartmentStore.DepartmentHead = DepartmentDetails(DeptID).Substring(5, 20).Trim.PadLeft(20)
DepartmentStore.DepartmentName = DepartmentDetails(DeptID).Substring(25, 10).Trim.PadLeft(20)
'Set the property in the class with the proper data type
DepartmentStore.DepartmentBudget = DepartmentBudget
'Then prepare a string for the writing to the fil
Dim PaddedBudget = CStr(DepartmentBudget).PadLeft(9)
sw.WriteLine(PaddedID & DepartmentStore.DepartmentHead & DepartmentStore.DepartmentName & PaddedBudget)
sw.Close()
'***********************Having Problems Here***********************
'This is using the path from the most recent dialog
DepartmentDetails = File.ReadAllLines(MyFilePath)
'Here you are changing the value of one of the elements in the DepartmentDetails array
DepartmentDetails(DeptID) = ""
'Public Shared Sub WriteAllLines (path As String, contents As String())
'The string "DepartmentDetails" is not a path
File.WriteAllLines(MyFilePath, DepartmentDetails)
'************************Having Problems Here**************************
YesNo = MessageBox.Show("Department has been billed. Would you like to delete the bill?", "Delete Bill?", MessageBoxButtons.YesNo)
If YesNo = DialogResult.Yes Then
End If
End Sub

VB.NET - List.Contains Returns False But Should be True

I had a look at List.Contains returns false, even though it seems it should return true but his code structure is a bit different to mine so im unsure if I have the same issue.
Before I continue, Let me explain what my result should be.
We have 2 input files, File 1 with email:hash's the other with a mix of email:hash and email:plain.
End output: If the Second file has plaintext after :, Output it (Making sure not to make duplicates when outputting file 1's email:hash's if no file 2 line for that email/hash is made), Otherwise output with the Hash.
tl;dr - Basically make the Second File overwrite prioritized over the First File.
(First File Randomized)
ABC_123#gmail.com:f6deea50e7eeb2d930fab83ccc32cdfe
123abc#domain.ext:82e6eeea4060c90cc3dc6ddd25885806
123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd
abc123#email.com:2d366131008f89781b8379bed3451656
(Second File Randomized)
123abc#domain.ext:aaaaaaaa
ABC_123#gmail.com:cccccccc
abc123#email.com:bbbbbbbb
newemail#hotmail.com:ddddddddd
Output should be:
123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd
123abc#domain.ext:aaaaaaaa
ABC_123#gmail.com:cccccccc
abc123#email.com:bbbbbbbb
newemail#hotmail.com:ddddddddd
(Output from Tests - "->" lines shouldn't be outputted.)
123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd
->123abc#domain.ext:82e6eeea4060c90cc3dc6ddd25885806
123abc#domain.ext:aaaaaaaa
ABC_123#gmail.com:cccccccc
->ABC_123#gmail.com:f6deea50e7eeb2d930fab83ccc32cdfe
abc123#email.com:bbbbbbbb
newemail#hotmail.com:ddddddddd
In the Second OpenFileDialog Block it always returns false until the LAST line in the For Each combo as Match in matches.
Weirdly, If I change the second regex from (.*)#(.*):(.*) to (.*)#(.*):([a-f0-9]{32}) it for some reason works, The issue with that is it will only match Email#domain.ext:{md5} and won't match for example Email#domain.ext:abc123 which is a requirement.
(Latest code update where I was messing around to try fix it broke it even more so this doesn't even work now).
I slept for once and came back on to try fix it, So far im almost there, It's overwriting correctly except for on one email:hash for some reason.
Image showing error
As you can see it changed the 123abc#domain.ext from the hash to aaaaaaa but for the ABC_123#gmail.com it didn't for some strange reason. Also yes the abc123#email.com hash does change so it's odd that a random email:hash didn't change.
I have been at this for about 9 12+ hours straight. (No Exaggeration) and i'd really love an enlightenment on what's going on.
I have tried so many alternatives and such that I can't even remember at this point.
Code: (Updated x3)
Reminder: Read above on what im trying to achieve :)
#Region "Merge Combo's"
Private Sub List_Merge_Click(sender As Object, e As EventArgs) Handles List_Merge.Click
Dim ofd = New OpenFileDialog()
ofd.Title = "Import..."
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
ofd.Filter = "Text files|*.txt"
ofd.Multiselect = True
'If the user selects 2 Files;
If (ofd.ShowDialog() = DialogResult.OK And ofd.CheckFileExists = True) Then
'Make sure there are no previously stored Conversions;
ActionList2.Items.Clear()
'Variables;
Dim MergedCombos As Integer = 0
Dim TotalCombos As Integer = 0
Try
For Each filename As String In ofd.FileNames
Using sr As New StreamReader(filename)
Dim result = filename.Union(filename, New MailEqualityComparer)
'Get all Matches found from the Regex Condition;
Dim combos As MatchCollection = New Regex("^([^#]+)#(.*):(.*)$", RegexOptions.Multiline).Matches(sr.ReadToEnd)
'Add each Match to the ActionList except for Duplicates;
For Each combo As Match In combos
'Increment the Total Combo's count;
TotalCombos += 1
'If the ActionList doesn't contain the same Combo;
If Not ActionList2.Items.Contains(combo.Value) Then
'If the email is already in the ActionList;
If IsInListbox(ActionList2, combo.Groups(1).Value + "#" + combo.Groups(2).Value) = True Then
'This combo is presumed to be a Hash Decrypted Combo - Overwrite it with the Encrypted Hash;
ActionList2.Items.Add(combo.Value)
'Remove the Hash Item from ActionList;
ActionList2.Items.RemoveAt(FindListboxIndex(ActionList2, combo.Groups(1).Value + "#" + combo.Groups(2).Value))
Else
'Add the Combo;
ActionList2.Items.Add(combo.Value)
End If
End If
Next
End Using
Next
Catch ex As Exception
Console.WriteLine("Error: " + ex.ToString)
Finally
'If atleast 1 Item is in the ActionList, Enable the Export Button;
If ActionList2.Items.Count > 0 Then
ExportButton.Enabled = True
ExportButton.BackColor = Color.FromArgb(149, 255, 141)
End If
'Update the Merged Combo's count;
StatusBar_LeftText.Text = MergedCombos.ToString
'If MergedCombos are less than TotalCombos, Add a "x Duplicates Removed" message;
If MergedCombos < TotalCombos Then
StatusBar_LeftText.Text += " - " + (TotalCombos - MergedCombos).ToString + " Duplicates Removed"
End If
'Autoscroll;
ActionList2.TopIndex = ActionList2.Items.Count - 1
End Try
End If
End Sub
Private Function FindListboxIndex(lb As ListBox, searchString As String) As Integer
For i As Integer = 0 To lb.Items.Count - 1
If lb.Items(i).ToString().Contains(searchString) Then
Return i
Exit Function
End If
Next
Return -1
End Function
Private Function IsInListbox(lb As ListBox, searchString As String) As Boolean
For i As Integer = 0 To lb.Items.Count - 1
If lb.Items(i).ToString().Contains(searchString) Then
Return True
Exit Function
End If
Next
Return False
End Function
#End Region
Hi, I think this should fit to your Needs.
Dim ofd = New OpenFileDialog()
ofd.Title = "Import..."
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
ofd.Filter = "Text files|*.txt"
ofd.Multiselect = True
Dim output As New Dictionary(Of String, String) 'key = mail, value = plain/hash
If (ofd.ShowDialog() = DialogResult.OK And ofd.CheckFileExists = True) Then
For Each filename As String In ofd.FileNames
Using sr As New StreamReader(filename)
Dim combos As MatchCollection = New Regex("(.*)#(.*):(.*)").Matches(sr.ReadToEnd)
For Each match As Match In combos
Dim tmp() As String = Split(match.ToString, ":")
tmp(1) = tmp(1).Replace(vbCr, "").Replace(vbLf, "") 'Delete carriage return
If Not output.ContainsKey(tmp(0)) Then
output.Add(tmp(0), tmp(1))
Else
If output(tmp(0)).Length = 32 Then 'condition whether to change the value or not. You need to design it to your needs.
output(tmp(0)) = tmp(1)
End If
End If
Next match
End Using
Next filename
End If
I don't know if there is a carriage return in your data. I tried with simple txt files and there was.
You need to change the condition to your needs. I saw the hashes have 32 signs and the plain text does not..
What you want is the union of the two set of lines you have and that's exactly what Enumerable.Union do provided we have a way to distinguish equal elements.
Starting from this we first define that equality comparer :
Class MailEqualityComparer
Implements IEqualityComparer(Of String)
Overloads Function Equals(mail1 As String, mail2 As String) As Boolean Implements IEqualityComparer(Of String).Equals
' assume input validated
Return mail1.Split(":"c)(0).Equals(mail2.Split(":"c)(0))
End Function
Overloads Function GetHashCode(mail As String) As Integer Implements IEqualityComparer(Of String).GetHashCode
' assume input validated
Return mail.Split(":"c)(0).GetHashCode
End Function
End Class
That is for this class two string are equal if their part before the : are equal.
Then you just have to do the Union using an instance of that class to ensure proper equality :
' file1 and file2 are String arrays
' they could be the result of File.ReadAllLines for example
Dim file1 = {
"ABC_123#gmail.com: f6deea50e7eeb2d930fab83ccc32cdfe",
"123abc#domain.ext:82e6eeea4060c90cc3dc6ddd25885806",
"123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd",
"abc123#email.com: 2d366131008f89781b8379bed3451656"
}
Dim file2 = {
"123abc#domain.ext: aaaaaaaa",
"ABC_123#gmail.com: cccccccc",
"abc123#email.com: bbbbbbbb",
"newemail#hotmail.com: ddddddddd"
}
' result is an IEnumerable(Of String)
' add ToArray (for example) if you want to materialize the result
Dim result = file2.Union(file1, New MailEqualityComparer) ' note the order ; it matters
' result content :
' ----------------
' 123abc#domain.ext: aaaaaaaa
' ABC_123#gmail.com: cccccccc
' abc123#email.com: bbbbbbbb
' newemail#hotmail.com: ddddddddd
' 123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd
It just leaves us with "how do we determine the order for Union parameters ?"
For that we have to have a way to know which file contains the "plain text" stuff, information you didn't provided at time of writing.
(Note: the same could have been achieved using Hashset(Of String) or SortedSet(Of String) and their UnionWith method)
[SortedSet requires an IComparer(Of String) instead of an IEqualityComparer(Of String)]
Edit after comment
If I understood correctly your comment (which I'm not sure) ; here is what could be done using a SortedSet :
Class MailComparer
Implements IComparer(Of String)
Function Compare(mail1 As String, mail2 As String) As Integer Implements IComparer(Of String).Compare
' assume input validated
Return mail1.Split(":"c)(0).CompareTo(mail2.Split(":"c)(0))
End Function
End Class
' file1 and file2 are String arrays
' they could be the result of File.ReadAllLines for example
Dim file1 = {
"ABC_123#gmail.com: f6deea50e7eeb2d930fab83ccc32cdfe",
"123abc#domain.ext:82e6eeea4060c90cc3dc6ddd25885806",
"123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd",
"abc123#email.com: 2d366131008f89781b8379bed3451656"
}
Dim file2 = {
"123abc#domain.ext: aaaaaaaa",
"ABC_123#gmail.com: cccccccc",
"abc123#email.com: bbbbbbbb",
"newemail#hotmail.com: ddddddddd"
}
' allLines is an IEnumerable(Of String)
Dim allLines = file2.Concat(file1) ' note the order ; it matters
Dim result As New SortedSet(Of String)(allLines, New MailComparer)
' result content :
' ----------------
' 123_ABC#gmail.com:8fa5104d4d995dc153e5509ab988bcfd
' 123abc#domain.ext: aaaaaaaa
' ABC_123#gmail.com: cccccccc
' abc123#email.com: bbbbbbbb
' newemail#hotmail.com: ddddddddd
I don't see where it's not simple using an 8 lines class ; but maybe I missed the point...

If third character Not IsNumeric

I'm working on a project that displays text on a monitor as a reference but running into some logic trouble. Someone clicks a button which prompts an InputBox into which they insert a bar code with a scanner.
I have 2 types of part numbers, one is like this "11n11110mch" the other is something like this "12311110mch". I need code that tests whether the 3rd character is a number. The end goal is to display the number as "11.(some letter)111.10 MCH" and "123.111.10 MCH" in a TextBox. If I try "11n22210mch", I get an error that says
Conversion from string "n" to type 'Double' is not valid.
at
thirdChara = Mid$(VisPartID, 3, 1)
I am not sure how to correct this or accomplish what I am trying to do.
The code I have:
Public Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
Dim ScanIDRaw As Object
'Clear Scan Value
ScanIDRaw = Nothing
'Display message, title, And default value.
ScanIDRaw = InputBox("Scan CDI", "InputBox")
Do Until ScanIDRaw IsNot ""
ScanIDRaw = InputBox("Part Number Needed, Scan CDI", "InputBox")
Loop
lblCDIPart.Text = ScanIDRaw
HUD.ReferenceCardDataPull()
End Sub
Public Async Sub ReferenceCardDataPull()
Dim PartID As String
Dim VisPartID As String
Dim thirdChara As String
'Other Code
'Something
'Something
VisPartID = Main.lblCDIPart.Text
thirdChara = Mid$(VisPartID, 3, 1)
If thirdChara = Not IsNumeric(thirdChara) Then
VisPartID = VisPartID.Insert(2, ".")
VisPartID = VisPartID.Insert(7, ".")
VisPartID = VisPartID.Insert(10, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
Else
VisPartID = VisPartID.Insert(3, ".")
VisPartID = VisPartID.Insert(8, ".")
VisPartID = VisPartID.Insert(11, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
End If
End Sub
If Not isNumeric(thirdChara) Then
But you really should be using VB.Net methods instead of the old VB6 style
dim position3 as integer
thirdChara = VisPartID.SubString(2,1) ' 2 because we're 0 based
if not integer.tryparse(thirdChara, position3) then
'do stuff if not a number
else
'it's a number
end if
The tryparse will return a boolean based upon the parse result. Upon successful parse, it will store the parsed value into the variable (in this case Position3)
I would also recommend turning on Option Strict as that would have informed you right away that you cannot implicitly convert a string to a boolean.
Meaning: The string thirdChara is being tested for equality against as Not (True|False) result from the IsNumeric method.

Search line in text file and return value from a set starting point vb.net

I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)