vb.net statusbar text doesn't show - vb.net

I have a code that searches for words in documents and fills a Listview with the found documents. Because the process can be rather lengthly I put a warning in the statusbar.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim foundList As Boolean
Dim docImage As VariantType
Dim PresetName As String
ListView1.Items.Clear()
ToolStripLabel1.Text = "Searching your documents, please wait."
Try
For Each row As DataRowView In CheckedListBox1.CheckedItems
SearchRegX = row("RegX")
Next
If TextBoxFreeText.Text <> "" Then
'look for a space in the search criteria, meaning there are more words
Dim counter As Integer = TextBoxFreeText.Text.IndexOf(" ")
If counter <> -1 Then
'more words were entered to search
Dim varSplit As Object
varSplit = Split(TextBoxFreeText.Text, " ")
'if more than two words are entered our regex doesnt work, so we exit the sub
If varSplit.length > 2 Then
MsgBox("Your search criteria are to complex, use a maximum of two words",, Title)
Exit Sub
End If
iWords = NumericUpDown1.Value
SearchRegX = "(?i)\b(?:" + varSplit(0) + "\W+(?:\w+\W+){0," + iWords + "}?" + varSplit(1) + "|" + varSplit(1) + "\W+(?:\w+\W+){0," + iWords + "}?" + varSplit(0) + ")\b"
Else
'just one word was entered
SearchRegX = "(?i)\b" + TextBoxFreeText.Text + "\b"
End If
End If
If SearchRegX = "" Then
MsgBox("No Keyword was selected",, Title)
Exit Sub
End If
If ListBox1.SelectedIndex > -1 Then
For Each Item As Object In ListBox1.SelectedItems
Dim ItemSelected = CType(Item("Path"), String)
SearchFolder = ItemSelected
'check if the folder of the archive still exists
If (Not System.IO.Directory.Exists(SearchFolder)) Then
Dim unused = MsgBox("The archive " + SearchFolder.Substring(SearchFolder.Length - 5, Length) + " was not found",, Title)
Continue For
End If
Dim dirInfo As New IO.DirectoryInfo(SearchFolder)
Dim files As IO.FileInfo() = dirInfo.GetFiles()
Dim file As IO.FileInfo
docImage = ImageList1.Images.Count - 1
Dim items As New List(Of ListViewItem)
For Each file In files
Dim filename As String = file.Name.ToString
If file.Extension = ".pdf" Or file.Extension = ".PDF" Then
foundList = PDFManipulation.GetTextFromPDF2(SearchFolder + filename, SearchRegX)
If foundList = True Then
If ListView1.FindItemWithText(filename.ToString) Is Nothing Then
items.Add(New ListViewItem(New String() {"", filename.ToString, SearchFolder.ToString}, docImage))
End If
End If
End If
Next
ListView1.Items.AddRange(items.ToArray)
Next
ToolStripLabel1.Text = ListView1.Items.Count.ToString + " Documents found."
Else
MsgBox("No archive was selected",, Title)
End If
SearchRegX = ""
SearchFolder = ""
'now save the search word to our textfile
PresetName = TextBoxFreeText.Text
If PresetName <> "" Then
AddSearchWord()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Somehow the text doesn't show in the statusbar before the process starts.
What should I change?
I thought about a BackgroundWorker showing an image like waiting but the BackgroundWorker doesn't work because inside my Sub I call a function elsewhere.

This happens because the status strip control is not rendered properly before the pending workload is finished. To do so, you can refresh the status strip manually:
StatusStrip1.Refresh()
That is, if your only goal is to set the text. If you thought about running the code in the background so that the form is still responsive to user input, you'll need asynchronous programming using System.Threading.Tasks or System.Threading.Thread to run the code as a seperate thread. Be aware though that you may face difficulties when trying to access controls outside of the main thread.

Add Async to your button handler declaration:
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Now change your call to PDFManipulation.GetTextFromPDF2() so that it is within a Task:
Await Task.Run(Sub()
foundList = PDFManipulation.GetTextFromPDF2(SearchFolder + filename, SearchRegX)
End Sub)
If foundList = True Then
...

Related

vb.NET You are not allowed to perform an operation across different threads

I am running code to read text from pdf files and than create a WordCloud. To inform the user the process is on going I add a BackgroundWorker to my form that shows an image saying Loading. I get an error for operating across different threads.
Private Sub ButtonCreate_Click(sender As Object, e As EventArgs) Handles ButtonCreate.Click
bTextEmpty = False
ListView1.Items.Clear()
ResultPictureBox.Image = Nothing
If ListBox1.SelectedIndex > -1 Then
For Each Item As Object In ListBox1.SelectedItems
Dim ItemSelected = CType(Item("Path"), String)
Dim myTempFile As Boolean = File.Exists(ItemSelected + "\Words.txt")
If myTempFile = False Then
'when we load the form we first call the code to count words in all files in a directory
'lets check if the folder exists
If (Not System.IO.Directory.Exists(ItemSelected)) Then
Dim unused = MsgBox("The archive " + ItemSelected.Substring(ItemSelected.Length - 5, Length) + " was not found",, Title)
Exit Sub
Else
Call CreateWordList(ItemSelected)
End If
End If
'if the words file is empty we cant create a cloud so exit the sub
If bTextEmpty = True Then Exit Sub
'then we fill the wordcloud and Listview from the created textfile
Call CreateMyCloud(ItemSelected + "\Words.txt")
Next
Else
Dim unused = MsgBox("You have to choose an Archive to create the Word Cloud",, Title)
End If
Size = New Drawing.Size(1400, 800)
End Sub
I put above code in a Private Sub and called it from my BackgroundWorker. The error occured at this line: If ListBox1.SelectedIndex > -1 Then
After trying the suggested code I get the same error again:
Public Sub CreateMyCloud(ByVal sourcePDF As String)
Dim WordsFreqList As New List(Of WordsFrequencies)
For Each line As String In File.ReadLines(sourcePDF)
Dim splitText As String() = line.Split(","c)
If splitText IsNot Nothing AndAlso splitText.Length = 2 Then
Dim wordFrq As New WordsFrequencies
Dim freq As Integer
wordFrq.Word = splitText(0)
wordFrq.Frequency = If(Integer.TryParse(splitText(1), freq), freq, 0)
WordsFreqList.Add(wordFrq)
End If
Next
If WordsFreqList.Count > 0 Then
' Order the list based on the Frequency
WordsFreqList = WordsFreqList.OrderByDescending(Function(w) w.Frequency).ToList
' Add the sorted items to the listview
WordsFreqList.ForEach(Sub(wf)
error -> ListView1.Items.Add(New ListViewItem(New String() {wf.Word, wf.Frequency.ToString}, 0))
End Sub)
End If
Dim wc As WordCloudGen = New WordCloudGen(600, 400)
Dim i As Image = wc.Draw(WordsFreqList.Select(Function(wf) wf.Word).ToList, WordsFreqList.Select(Function(wf) wf.Frequency).ToList)
ResultPictureBox.Image = i
End Sub
Should look something more like:
Private Sub ButtonCreate_Click(sender As Object, e As EventArgs) Handles ButtonCreate.Click
If ListBox1.SelectedItems.Count > 0 Then
Dim data As New List(Of Object)
For Each Item As Object In ListBox1.SelectedItems
data.Add(Item)
Next
bTextEmpty = False
ListView1.Items.Clear()
ResultPictureBox.Image = Nothing
BackgroundWorker1.RunWorkerAsync(data)
Else
MessageBox.Show("You have to choose an Archive to create the Word Cloud",, Title)
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim data As List(Of Object) = DirectCast(e.Argument, List(Of Object))
For Each Item As Object In data
Dim ItemSelected = CType(Item("Path"), String)
Dim myTempFile As Boolean = File.Exists(ItemSelected + "\Words.txt")
If myTempFile = False Then
'when we load the form we first call the code to count words in all files in a directory
'lets check if the folder exists
If (Not System.IO.Directory.Exists(ItemSelected)) Then
MessageBox.Show("The archive " + ItemSelected.Substring(ItemSelected.Length - 5, Length) + " was not found",, Title)
Exit Sub
Else
Call CreateWordList(ItemSelected)
End If
End If
'if the words file is empty we cant create a cloud so exit the sub
If bTextEmpty = True Then Exit Sub
'then we fill the wordcloud and Listview from the created textfile
Call CreateMyCloud(ItemSelected + "\Words.txt")
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Size = New Drawing.Size(1400, 800)
End Sub
To fix the error in your second, edited post:
WordsFreqList.ForEach(Sub(wf)
ListView1.Invoke(Sub()
ListView1.Items.Add(New ListViewItem(New String() {wf.Word, wf.Frequency.ToString}, 0))
End Sub)
End Sub)
You cannot simply access controls outside of the current thread. You first need to call the Invoke method on the target control and then pass a delegate containing the instructions intended to modify the control outside of the current thread. See this article on MSDN on how to do this: https://learn.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls?view=netframeworkdesktop-4.8

How to get ListView.SubItems

I'm trying to make a program that inputs text into a document depending on the user input, and I am currently displaying it as a ListView.
I can't figure out how to get the SubItem from the item, as this is my current code.
For Each item In ListView1.Items
Dim inputString72 As String = "#bot.command()" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString72, True)
Dim inputString73 As String = "async def " + item.Text + "(ctx):" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString73, True)
Dim inputString74 As String = " await ctx.send('" + THE SUBITEM OF THE ITEM GOES HERE + "')" + vbNewLine
My.Computer.FileSystem.WriteAllText(
SaveFileDialog1.FileName, inputString74, True)
Next
I think it would be more efficient to use the .net File class. No need to call the method several times in each iteration. From the docs. "The WriteAllText method opens a file, writes to it, and then closes it. " That is a lot of openning and closing. Build a string with a StringBuilder (which is mutable) and then write once to the file.
I used interpolated strings (it is preceded by a $) which allows you to put a variable directly in a string surrounded by braces.
SubItem indexes start at 0 with the first column. The .Text property of the SubItem will return its contents.
Private Sub WriteListViewToFile(FilePath As String)
Dim sb As New StringBuilder
For Each item As ListViewItem In ListView1.Items
sb.AppendLine("#bot.command()")
sb.AppendLine($"async def {item.Text}(ctx):")
sb.AppendLine($" await ctx.send('{item.SubItems(1).Text}')")
Next
File.WriteAllText(FilePath, sb.ToString)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
WriteListViewToFile(SaveFileDialog1.FileName)
End If
End Sub

exceeding bounds of array in VB

I have an assignmemnt for school, "Create a txt file with to fill a 5x8 array. I can read from the file fine, however, i keep getting System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' I know this means my index is exceeding my array bounds, however it should not be, at least that i can tell. any help would be appreciated. Code listed below in full...Error is coming from the private sub stansgrocery_load
Public Class StansGrocery
Dim fileNameString As String = "C:\Users\lisht\Dropbox\Lish\Week 4\Stans\Grocerys.txt" 'Setting the preloaded location for my grocery.txt file
Dim Food$(4, 7) 'setting the boundaries of the array
Private Sub ReadFile(ByVal fileNameString As String, ByRef recordData() As String)
fileNameString = "C:\Users\lisht\Dropbox\Lish\Week 4\Stans"
Dim ptr, hell, cold As Int32
itemsComboBox.Items.Clear()
Dim currentRecordString, fileDataString As String
Dim fileNumberInt As Integer = FreeFile()
'Reads in a file with the first argument being it's location, and the second an array. The functions FileOpen, and Input use the filename to
'identify the file location, and filenumber, which is set by freefile, to identify the file.
Do
Try
FileOpen(1, fileNameString, OpenMode.Input) 'Opening the file
hell = 0
Catch ex As Exception
hell = 1
Me.OpenFileDialog1.FileName = fileNameString
Me.OpenFileDialog1.ShowDialog()
fileNameString = OpenFileDialog1.FileName
End Try
Loop Until hell = cold
recordData = Split(fileDataString, "$$") 'splitting the words for each deliminator of "$$"
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles searchTextbox.TextChanged
'This is the only way to close the program, by having the textbox check for change and seeing
'"zzz" the form will close.
If searchTextbox.Text = "zzz" Then Me.Close()
End Sub
Private Sub StansGrocery_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'On load reads in the file with ReadFile Sub.
Dim originalFileName As String = "C:\Users\lisht\"
Dim inventoryIn() As String
'The first read in information is an empty string, so by Dimensioning i at 1 the first blank is always skipped, and also resets with each load.
Dim i As Integer
ReadFile(originalFileName, inventoryIn)
For aisle = 0 To 4
For item = 0 To 7
Food(aisle, item) = inventoryIn(i)
itemsComboBox.Items.Add(inventoryIn(i))
i += 1
Next
Next
End Sub
Private Sub InventoryComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles itemsComboBox.SelectedIndexChanged
'Loops through each array position and checks to see if the item is equal to the Combo box selected item. Then shows its aisle and number,
'by adding one to it's array index row and column. If it is found it displays a message with the location.
For aisle = 0 To 4
For item = 0 To 7
If Food(aisle, item) Is itemsComboBox.SelectedItem Then
Label1.Text = ("You will find " & Food(aisle, item) & " on aisle #" & aisle + 1 & ", item # " & item + 1)
End If
Next
Next
End Sub
Private Sub searchTextBoxButton_Click(sender As Object, e As EventArgs) Handles searchTextBoxButton.Click
'Initiaties a search, and sets isFound to it's default "Item not found" message.
Dim isFound As String = "The item you are searching for is not in the store"
'Loops through each array position and checks to see if the item is equal to the read in text.
'Then shows its aisle and number, by adding one to it's array index row and column. If it is found it displays a message with the location.
For aisle = 0 To 4
For Item = 0 To 7
If Food(aisle, Item).ToLower = searchTextbox.Text.ToLower Then
'updates isFound if the item is found.
isFound = "You will find " & Food(aisle, Item) & " on aisle #" & aisle + 1 & ", item #" & Item + 1
End If
Next
Next
'Displays the location of the item, or the "Item not found message.
Label1.Text = (isFound)
searchTextbox.Clear()
End Sub
End Class

VB.Net Webclient Upload Hanging

I have multiple files to upload (to FTP server) using this code:
Private Sub UploadFile(ByVal local As String)
If wc.IsBusy = True Then Throw New Exception("An upload is already ongoing!")
wc.Credentials = New NetworkCredential(usr.ToString, pass.ToString) 'Set the credentials.
'total_dl_size = GetDownloadSize(url) 'Get the size of the current file.
Try
Dim FileName As String = Path.GetFileName(local) 'Get the current file's name.
AppendWarning("Uploading " & FileName & "... ") 'Download notice.
wc.UploadFileAsync(New Uri(info_srv & local), Path.Combine(mc_dir, local)) 'Download the file to the desktop (use your own path here).
Catch ex As Exception
AppendWarning("-ERR: Could not download file: " & local & ControlChars.NewLine)
End Try
End Sub
Private Sub AppendWarning(ByVal Text As String)
If tb_warnings.InvokeRequired Then
tb_warnings.Invoke(Sub() tb_warnings.AppendText(Text))
Else
tb_warnings.AppendText(Text)
End If
End Sub
Private Sub wc_UploadProgressChanged(sender As Object, e As System.Net.UploadProgressChangedEventArgs) Handles wc.UploadProgressChanged
total_ul = e.BytesSent
Dim Progress As Integer = CType(Math.Round((baseline + total_ul) * 100) / total_ul_size, Integer)
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(Sub()
If Progress > 100 Then Progress = 100
If Progress < 0 Then Progress = 0
ProgressBar1.Value = Progress
End Sub)
Else
If Progress > 100 Then Progress = 100
If Progress < 0 Then Progress = 0
ProgressBar1.Value = Progress
End If
If lbl_progress.InvokeRequired Then
lbl_progress.Invoke(Sub() lbl_progress.Text = ((total_ul + baseline) / 1024).ToString("N0") & " KB / " & (total_ul_size / 1024).ToString("N0") & " KB")
Else
lbl_progress.Text = ((total_ul + baseline) / 1024).ToString("N0") & " KB / " & (total_ul_size / 1024).ToString("N0") & " KB | " & Progress.ToString & "%"
End If
End Sub
Private Sub wc_uploadFileCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs) Handles wc.UploadDataCompleted
If e.Cancelled Then
MessageBox.Show(e.Cancelled)
ElseIf Not e.Error Is Nothing Then
MessageBox.Show(e.Error.Message)
Else
If files.Count > 0 Then
AppendWarning("Upload Complete!" & ControlChars.NewLine)
baseline = baseline + total_ul
Dim file As String = files.Dequeue()
MsgBox(file)
UploadFile(file) 'Download the next file.
Else
AppendWarning("All Uploads Finished!" & ControlChars.NewLine)
End If
End If
However, using my two test files, it always stops at what would otherwise be the end of the first file I've given it, and doesn't go onto the second one.
However, I have an FTP client connected to this same server, and when I refresh I can see (at least for the first file) the data is being properly uploaded.
Any suggestions as to what's going wrong here?
Edit, log: http://pastebin.com/kqG28NGH
Thank you for any assistance!
This works for me...I tried to mimic what I think is in your form. I tested with a queue of 8 files ranging from 150K to 400K each. I couldn't quite work out what you were trying to do with the progress bar. Mine fills for each file and resets for the next, finishing empty with the last call to DoUpload where there are no more files. Hopefully, this will help.
Imports System.IO
Imports System.Net
Public Class Form1
Const info_srv As String = "ftp://example.com/SomeFolder/"
Const usr As String = ""
Const pass As String = ""
Const mc_dir As String = "D:\Source\Folder"
Private WithEvents wc As New Net.WebClient
' Contains file names only, no paths
Private Files As New Queue(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
wc.Credentials = New NetworkCredential(usr, pass)
' Put the work in a task so UI is responsive
Task.Run(Sub() DoUpload())
End Sub
Private Sub DoUpload()
ShowProgress("", 0)
If Files.Count > 0 Then
Dim local As String = Files.Dequeue
Dim FileName As String = Path.Combine(mc_dir, local)
AppendWarning("Uploading " & FileName & "... ")
Try
wc.UploadFileAsync(New Uri(info_srv & local), FileName)
Catch ex As Exception
AppendWarning("-ERR: Could not upload file: " & local & Environment.NewLine)
End Try
Else
AppendWarning("All Uploads Finished!" & Environment.NewLine)
End If
End Sub
Private Sub wc_UploadProgressChanged(sender As Object, e As UploadProgressChangedEventArgs) _
Handles wc.UploadProgressChanged
' Do not use e.ProgressPercentage - it's inaccurate by half by design per Microsoft
With String.Format("{0} KB / {1} KB", Int(e.BytesSent / 1024).ToString("N0"), Int(e.TotalBytesToSend / 1024).ToString("N0"))
ShowProgress(.ToString, Int(e.BytesSent / e.TotalBytesToSend * 100))
End With
End Sub
Private Sub wc_UploadFileCompleted(sender As Object, e As UploadFileCompletedEventArgs) _
Handles wc.UploadFileCompleted
Select Case True
Case e.Cancelled
MessageBox.Show("Cancelled")
Case e.Error IsNot Nothing
MessageBox.Show(e.Error.Message)
Case Else
AppendWarning("Upload Complete!" & Environment.NewLine)
' I needed this just so I could see it work, otherwise too fast
Threading.Thread.Sleep(500)
DoUpload()
End Select
End Sub
Private Sub AppendWarning(ByVal Text As String)
If Me.InvokeRequired Then
Me.Invoke(Sub() AppendWarning(Text))
Else
tb_warnings.AppendText(Text)
End If
End Sub
Private Sub ShowProgress(LabelText As String, Progress As Integer)
If Me.InvokeRequired Then
Me.Invoke(Sub() ShowProgress(LabelText, Progress))
Else
Me.lbl_progress.Text = LabelText
Me.lbl_progress.Refresh()
Me.ProgressBar1.Value = Progress
Me.ProgressBar1.Refresh()
End If
End Sub
End Class
For posterity:
Check your network trace settings in the VB config. I used a really verbose catch-all config I found to do the trace, but it seems the overhead was killing the upload. I've since found a much leaner focus-on-ftp set of xml to modify this and the files now upload properly. Thank you everyone!

VB Populating ComboBox with specific field from comma-delimited txt file

Need to populate NameComboBox from a comma-delimited txt file. Want user to be able to select just the name from NameComboBox dropdown and the rest of the textboxes to fill in.
Right now the entire record is populating the ComboBox.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim NameString As String
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
NameString = ContactInfoStreamReader.ReadLine()
NameComboBox.Items.Add(NameString)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
****Update 11/2/15:
The names are appearing in the NamesComboBox as they should but when one is selected the info doesn't show in the other text boxes. Also as soon as form loads its already putting info in the other textboxes (from the 1st record in the array) before any name is selected from NamesComboBox.
Heres my streamwrite form
Imports System.IO
Public Class ContactInfoForm
' Declare module-level variable.
Private ContactInfoStreamWriter As StreamWriter
Private Sub SaveButton_Click(sender As System.Object, e As System.EventArgs) Handles SaveButton.Click
' Save the users contact information to the end of the file.
' Make sure name field and at least 1 number field is not empty.
If NameTextBox.Text <> "" And PhoneNumberTextBox.Text <> "" Or PagerNumberTextBox.Text <> "" Or
CellPhoneNumberTextBox.Text <> "" Or VoiceMailNumberTextBox.Text <> "" Then
If ContactInfoStreamWriter IsNot Nothing Then ' Check if the file is open
Dim info As String = ""
info = String.Format("{0},{1},{2},{3},{4},{5}", _
NameTextBox.Text, PhoneNumberTextBox.Text, PagerNumberTextBox.Text,
CellPhoneNumberTextBox.Text, VoiceMailNumberTextBox.Text, EmailAddressTextBox.Text)
ContactInfoStreamWriter.WriteLine(info)
With NameTextBox
.Clear()
.Focus()
End With
PhoneNumberTextBox.Clear()
PagerNumberTextBox.Clear()
CellPhoneNumberTextBox.Clear()
VoiceMailNumberTextBox.Clear()
EmailAddressTextBox.Clear()
Else ' File is not open
MessageBox.Show("You must open the file before you can save your contact information.", "File is Not Open",
MessageBoxButtons.OK, MessageBoxIcon.Information)
' Display the File Open dialog box.
OpenToolStripMenuItem_Click(sender, e)
End If
Else
MessageBox.Show("Please enter your name and at least 1 number where you can be reached.", "Data Entry Error",
MessageBoxButtons.OK)
NameTextBox.Focus()
End If
End Sub
Heres my Streamread section on the form to lookup in combo box.
Imports System.IO
Public Class LookupForm
Private Sub LookupForm_Load(sender As Object, e As System.EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Dim LineString As String
Dim FieldString As String()
Try
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("C:\Users\Cherokee\Documents\Cherokees Files\School Stuff\Visual Basic\Week 8 Data Files\pg465Ex11.5\pg465Ex11.5\pg465Ex11.5\bin\Debug\TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
LineString = ContactInfoStreamReader.ReadLine()
FieldString = LineString.Split(CChar(","))
LineString = FieldString(0) 'Take First Field
NameComboBox.Items.Add(LineString)
'Set Textboxes based on position in line.
PhoneNumberTextBox.Text = FieldString(1)
PagerNumberTextBox.Text = FieldString(2)
CellPhoneNumberTextBox.Text = FieldString(3)
VoiceMailNumberTextBox.Text = FieldString(4)
EmailAddressTextBox.Text = FieldString(5)
Loop
' Close the file.
ContactInfoStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("Create a new file?", "File Not Found",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If ResponseDialogResult = Windows.Forms.DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
You can Split the line read and take the column position you require as for example if first column is the name then your code becomes as below:
' Open the file.
Dim ContactInfoStreamReader As StreamReader = New StreamReader("TextFile.txt")
' Read all the elements into the list.
Do Until ContactInfoStreamReader.Peek = -1
String lineRead = ContactInfoStreamReader.ReadLine()
Dim fields as String() = lineRead.Split(",")
NameString = fields(0) 'Take First Field
NameComboBox.Items.Add(NameString)
'Set Textboxes based on position in line.
'E.g. if Age is column 2 then
AgeTextBox.Text = fields(1)
Loop
' Close the file.
ContactInfoStreamReader.Close()