persisting textbox text in visual basic - vb.net

I am pretty new to VB and am compiling a program which contains several forms, each of which is populated with text boxes. The purpose of the program is for text to be dragged between boxes to move assets around. I've managed the drag and drop functionality but need to persist the text in the text boxes once the program is shut down so that when reopened, the last location of all moved text is still present.
Can anyone make any suggestions/supply sample code please?
I've tried the easiest to understand suggestion to get me started but when I build and publish the program it says that I do not have access to the file to save the values!! Can anyone help? Code below
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim txtpersist As IO.TextWriter = New IO.StreamWriter("C:\Users\HP\Documents\namestore")
txtpersist.WriteLine(TextBox1.Text)
txtpersist.WriteLine(TextBox2.Text)
txtpersist.WriteLine(TextBox3.Text)
txtpersist.Close()
Dim yourfile As IO.TextReader = New IO.StreamReader("C:\Users\HP\Documents\namestore")
TextBox1.Text = yourfile.ReadLine()
TextBox2.Text = yourfile.ReadLine()
TextBox3.Text = yourfile.ReadLine()
yourfile.Close()
End Sub
End Class

You can use the built in PropertyBinding to link your TextBox.Text to a Property. It will put it into your App.Config File which will allow you to edit it through MySettings as long as it is per user. If the settings are application level you would be better of using one of the other answers. You can also look at this article for some more information.

You should write the location of the textboxes to a persistent store on program exit, such as a file, a database, or the registry. On program load, you can retrieve the saved values and set the locations accordingly.

You could save each textbox's text inside of a file and re-open it at runtime.
Dim yourfile As TextWriter = New StreamWriter("pathtofile")
Say you had 3 textBoxes called textBox1, textBox2 and textBox3. You would save each one's status by simply writing each textbox's text property inside the file. Like so:
yourfile.WriteLine(textBox1.Text)
yourfile.WriteLine(textBox2.Text)
yourfile.WriteLine(textBox3.Text)
At the end, you just close the file.
yourfile.Close()
Loading the data back is just as simple.
Dim yourfile As TextReader = New StreamReader("pathtofile")
textBox1.Text = yourfile.ReadLine()
textBox2.Text = yourfile.ReadLine()
textBox3.Text = yourfile.ReadLine()
yourfile.Close()
Let me know if you have any questions or require further assistance. Be sure to import the System.IO namespace, to get access to the IO classes used here.

The most common method of persisting data is to store it in a database. Of course that adds more work to your project since you now have to create, update, and maintain a database. An easier solution is to use a file.
We'll create a new class in order to read & write data from the file. This way if you switch to a database later on, you only need to change the class. And since I'm sure at some point you'll want a database we'll make the class use datatables to minimize the changes needed to it. Here's our class:
Public Class TextBoxes
Private tbl As DataTable
Private filename As String
'Use constants for our column names to reduce errors
Private Const ctrlName As String = "CtrlName"
Private Const text As String = "Text"
Public Sub New(ByVal file As String)
'Create the definition of our table
tbl = New DataTable("TextBox")
tbl.Columns.Add(ctrlName, Type.GetType("System.String"))
tbl.Columns.Add(text, Type.GetType("System.String"))
'Save the filename to store the data in
Me.filename = file
End Sub
Public Sub Save(ByVal frm As Form)
Dim row As DataRow
'Loop through the controls on the form
For Each ctrl As Control In frm.Controls
'If the control is a textbox, store its name & text in the datatable
If TypeOf (ctrl) Is TextBox Then
row = tbl.NewRow
row.Item(ctrlName) = ctrl.Name
row.Item(text) = ctrl.Text
tbl.Rows.Add(row)
End If
Next
'Save the additions to the dataset and write it out as an XML file
tbl.AcceptChanges()
tbl.WriteXml(filename)
End Sub
Public Sub Load(ByVal frm As Form)
'Don't load data if we can't find the file
If Not IO.File.Exists(filename) Then Return
tbl.ReadXml(filename)
For Each row As DataRow In tbl.Rows
'If this control is on the form, set its text property
If frm.Controls.ContainsKey(row.Item(ctrlName)) Then
CType(frm.Controls(row.Item(ctrlName)), TextBox).Text = row.Item(text).ToString
End If
Next
End Sub
End Class
Next you'll want to use this fine class to read & write your data. The code for doing this is nice and simple:
Dim clsTextBoxes As New TextBoxes("C:\Txt.xml")
'Save the textboxes on this form
clsTextBoxes.Save(Me)
'Load the textboxes on this form
clsTextBoxes.Load(Me)

I would do it using either the Application settings as Mark Hall pointed out or like this...
Public Class MyTextBoxValueHolder
Public Property Value1 As String
Public Property Value2 As String
Public Property Value3 As String
Public Sub Save(Path As String)
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamWriter As New StreamWriter(Path)
serializer.Serialize(streamWriter, Me)
End Using
End Sub
Public Shared Function Load(Path As String) As MyTextBoxValueHolder
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamReader As New StreamReader(Path)
Return DirectCast(serializer.Deserialize(streamReader), MyTextBoxValueHolder)
End Using
End Function
End Class
So what you can then do is...
Dim myValues As MyTextBoxValueHolder = MyTextBoxValueHolder.Load("SomeFilePath.xml")
myTextBox1.Text = myValues.Value1
myTextBox2.Text = myValues.Value2
'And so on....
2 Save
Dim myValues As New MyTextBoxValueHolder
myValues.Value1 = myTextBox1.Text
myValues.Value2 = myTextBox2.Text
myValues.Save("SomeFilePath.xml")
'All saved

to maintain the values ​​you can use stored user settings, see the following links.
http://msdn.microsoft.com/en-us/library/ms379611(v=vs.80).aspx
http://www.codeproject.com/KB/vb/appsettings2005.aspx
Regards.

Related

Is there a way to extract a variable from a subroutine in vb .net? or how do I declare custom event handlers and trigger them in a linked fashion?

I am trying to build this file copy utility in VB.Net, and I have this window:
The current folder button opens up a folder browser dialog, and I save the selected path from the dialog to a string variable which I then pass to a function. The function adds all files and directories present in that folder to the current folder listbox.
Now I need this filepath for the all files checkbox, which when triggered lists all the subdirectories and their contents in the currentfolder listbox.
Is there any way I can extract that filepath variable dynamically without hardcoding it? Or can I create custom event handlers and trigger them inside the current folder button handler?
Here is my code:
Public Class Form1
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FB As FolderBrowserDialog = New FolderBrowserDialog()
Dim srcpath As String
Dim flag As Integer = 1
FB.ShowDialog()
FB.ShowNewFolderButton = True
If (DialogResult.OK) Then
srcpath = FB.SelectedPath()
End If
listfiles(srcpath)
End Sub
Public Function listfiles(srcpath As String)
Dim dir As DirectoryInfo = New DirectoryInfo(srcpath)
Dim dirs As DirectoryInfo() = dir.GetDirectories()
Dim d As DirectoryInfo
Dim files As FileInfo() = dir.GetFiles()
Dim file As FileInfo
For Each file In files
CurrentFolderListBox.Items.Add(file.Name)
Next
For Each d In dirs
CurrentFolderListBox.Items.Add(d)
Next
'If CheckBox1.Checked = True Then
' CheckBox1_CheckedChanged(sender, New System.EventArgs())
'End If
End Function
Public Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChange
Dim item As DirectoryInfo
For Each i As DirectoryInfo In CurrentFolderListBox.Items
item = i
Next
End Sub
Any help would be most appreciated.
Well, for the list side lbox, and the right side lbox?
Why not fill each list box with a data source? You can have 1, or 2, or even 5 columns of data. The ListBox can display TWO of the columns.
So, VERY often a list box will have two values. the "value" based on what you select (often a PK database row value), and then you have the "text" value for display.
from FoxPro, ms-access, vb.net, and even asp.net?
A list box traditional has had the ability to "store" a set of values for your selection.
So, why not just put out the file list to a on the fly "data structure". You can quite much use a struct, a class or whatever.
However, might as well use a data table, since listbox supports "binding" to a table.
So, in the ListBox settings, you have these two settings:
so above is our "display"
And then set the "value" to the FULL file name like this:
So now we can say create a form like this:
So, our code to select the "from folder" can look like this:
Private Sub cmdSelFrom_Click(sender As Object, e As EventArgs) Handles cmdSelFrom.Click
Dim f As New FolderBrowserDialog
If f.ShowDialog = DialogResult.OK Then
txtFromFolder.Text = f.SelectedPath
ListBox1.DataSource = GetFileData(txtFromFolder.Text)
End If
End Sub
Public Function GetFileData(sFolder As String) As DataTable
Dim rstData As New DataTable
rstData.Columns.Add("FullFile", GetType(String))
rstData.Columns.Add("FileName", GetType(String))
' get all files from this folder
Dim folder As New DirectoryInfo(sFolder)
Dim fList() As FileInfo = folder.GetFiles
For Each MyFile As FileInfo In fList
Dim OneRow As DataRow = rstData.NewRow
OneRow("FullFile") = MyFile.FullName
OneRow("FileName") = MyFile.Name
rstData.Rows.Add(OneRow)
Next
Return rstData
End Function
so, we setup a two column "thing" (in this case a data table).
We fill it with our two values (FileName and FullFile).
So, we now have this:
I have selected two files on the left side, and thus we get this:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
For Each MySel As DataRowView In ListBox1.SelectedItems
Debug.Print(MySel.Item("FileName"))
Debug.Print(MySel.Item("FullFile"))
Next
End Sub
OutPut:
a.pdf
C:\Test2\a.pdf
b.pdf
C:\Test2\b.pdf
We could even include say file size in that table. But the "basic" concept here is that we can store + save data items into the list box, and that REALLY makes the code simple, since the list box now has JUST the file for display, but also enables us to have the full path name also.

How to pass a form, object or data to a second form

I have created 2 forms.
The first one is the button that you want to back up.
In the second there are paths that can be modified.
How to make a reference that after pressing the "backup" button will get a path of 2 forms.
The path is saved when I closed form2
I know how to do it in one form but unfortunately I can not refer to another form.
Source of Form 2:
Private Sub Browser_from1_Click(sender As Object, e As EventArgs) Handles Browser_from1.Click
Dim FolderBrowserDialog1 As New FolderBrowserDialog
FolderBrowserDialog1.ShowDialog()
TextBox1from.Text = FolderBrowserDialog1.SelectedPath
If Browser_from1.Text <> "" And TextBox1from.Text <> "" Then
Backup.StartCopy.Enabled = True
End If
End Sub
Private Sub Browser_to1_Click(sender As Object, e As EventArgs) Handles Browser_to1.Click
Dim FolderBrowserDialog1 As New FolderBrowserDialog
FolderBrowserDialog1.ShowDialog()
TextBox2to.Text = FolderBrowserDialog1.SelectedPath
If Browser_to1.Text <> "" And TextBox2to.Text <> "" Then
Backup.StartCopy.Enabled = True
End If
End Sub
Private Sub TextBox1from_TextChanged(sender As Object, e As EventArgs) Handles TextBox1from.TextChanged
End Sub
Private Sub save_settings_Click(sender As Object, e As EventArgs) Handles save_settings.Click
My.Settings.pathmem = TextBox2to.Text
My.Settings.pathmem1 = TextBox1from.Text
My.Settings.Save()
End Sub
Private Sub setting_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1from.Text = My.Settings.pathmem1
TextBox2to.Text = My.Settings.pathmem
End Sub
End Class
You dont want to create a reference to a form - that would (or could) create a whole new form. You want to hold onto the form reference.
This is done by passing a reference to the forms, but the talk of one form fiddling with the controls on another form is a bad idea because it breaks encapsulation. But forms are classes (it says so at the top of each one), so you can add Properties and Methods (Sub and/or Functions) to facilitate passing information back and forth.
Method One - Passing a Form Reference
The simplest way is to pass whatever the other form needs in the constructor:
' form 1 / "main" form / form to return to
Dim frm As New Form6(Me)
frm.Show()
Me.Hide()
In order for this to work, you need to modify the constructor (Sub New) on the destination form:
Private frmReturnTo As Form
Public Sub New(f As Form)
' This call is required by the designer.
InitializeComponent()
frmReturnTo = f
End Sub
It is best not to create your own constructor until you are familiar with them. Use the drop downs at the top of the code window: from the left pick the form name; from the right, select New. The designer adds required code to them which must not be changed.
Do not add any code before the InitializeComponent() call at least until you are familiar with the life cycle of a form. The form and its controls do not exist until that runs.
To return to the "main" form:
If frmReturnTo IsNot Nothing Then
frmReturnTo.Show()
End If
You may want to remove some of the title bar buttons or add code to the form Closing event to handle when the user closes via the system menu or buttons.
Using the constructor is ideal for cases where there is some bit of data which the form must have in order to do its job.
Method Two - Passing Data
Thats all well and good, but what about passing data to another form? You can use the constructor for that too. In order to pass say, a string, integer and a Point:
' destination / second form:
Public Sub New(a As String, b As Int32, c As Point)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Label1.Text = a
Label2.Text = b.ToString
Label3.Text = c.ToString
End Sub
Call it like this:
' method two: pass data you want to share in the ctor
Dim frm As New frmData("hello", 6, New Point(150, 550))
frm.Show()
Result:
Method Three: Properties
Thats fine, but if there is a lots of data that way can get cumbersome. Plus, you may want to update some of the data from the calling/main form. For this you can create Properties on the form to handle the data:
Public Property Label1Text As String
Get
Return Me.Label1.Text
End Get
Set(value As String)
Me.Label1.Text = value
End Set
End Property
Rather than a private variable to act as the backing field, one of the controls is used. The name leaves a bit to be desired as it exposes implementation details. So, use names which describe what the data represents rather than where it displays.
Public Property SpecialValue As Integer
Get
Return Integer.Parse(Me.Label2.Text)
End Get
Set(value As Integer)
Me.Label2.Text = value.ToString
End Set
End Property
Public Property SomePoint As Point
Get
Dim data = Me.Label3.Text.Split(","c)
Return New Point(Convert.ToInt32(data(0)),
Convert.ToInt32(data(1))
)
End Get
Set(value As Point)
Me.Label3.Text = value.X.ToString & "," & value.Y.ToString
End Set
End Property
A point was used just to show that other data types can be used. Setting those values from the calling/original/source form:
Using frm As New Form6
frm.Label1Text = "Ziggy"
frm.SpecialValue = 42
frm.SomePoint = New Point(111, 222)
frm.ShowDialog()
' do stuff here with any changes
Dim theint = frm.SpecialValue
End Using ' dispose of dialog
The destination controls would well have been TextBoxes for the user to edit. The Property "wrappers" allow you to fetch those values back, so in this case, a Dialog was used.
Method Four: Methods
You can also use methods as a way to pass data to the second/helper form. Here a List(of T) collection will be passed. In the child/display form a method is added to receive the data which it then displays. The task represented is proofing or viewing a filtered list:
Public Sub UpdateDisplay(lst As List(Of SimpleItem), filter As String)
DataGridView1.DataSource = lst
Label1.Text = String.Format("{0} Total {1} Items", lst.Count, filter)
End Sub
In the main/calling form:
' form level variable
Private frmDV As frmDataView
elsewhere...perhaps in a Click event:
' myList is a simple list of items
' Users pick which color to filter on via a combo box
Dim filter As String
If cboListFilter.SelectedItem IsNot Nothing Then
'Dim frmDV As New frmDataView
If frmDV Is Nothing OrElse frmDV.IsDisposed Then
frmDV = New frmDataView
End If
filter = cboListFilter.SelectedItem.ToString()
' apply the filter
Dim tmpList = myList.Where(Function(w) w.Color = filter).ToList()
frmDV.UpdateDisplay(tmpList, filter)
frmDV.Show()
Else
Return
End If
Result:
With DataBased apps a modified version of this can allow for the case where you display DataGridView data in detail form on another form. You need not have the second form rung SQL to add or update the record, and then the main form running another query to "refresh" the display. If the DataSource is a DataTable backed up by a fully configured DataAdapter, pass the DataTable and have the child form add, change or delete using that. The data will automagically be in the DataTable and DataGridView`.
There are other ways to do this, but they generally all boil down to passing something from A to B. Which way is "best" depends on what the app does, the use-case and the nature of the data. There is no one right way or best way.
For instance, Properties and in many cases Functions allow the B Form to close the feedback loop. With DB items, a DataChanged property might tell the calling form that data was added or changed so that form knows to use the DataAdapter to update the db.
'SECOND FORM
Public class secondForm (blah blah)
Public overloads property owner as myMainForm
'Must be only the form you prepared for that
Private sub secondForm_load(blah blah) handles blah blah
Texbox1.text=Owner.customcontrol.text
End sub
End class
'MAIN FORM
public class myMainForm(blah blah)
Private sub button1_click(blah blah) handles blah blah
Dim NewSecondForm as secondForm = New secondForm
NewSecondForm.owner(me)
NewSecondForm.show(me)
NewSecondForm.dispose()
' so you can have bidirectional communication between the two forms and access all the controls and properties from each other
End sub
End Class

.NET Delete actual files from listbox

This code is intended to delete the actual files from the system when it is selected from the system:
Dim file As String()
file = System.IO.Directory.GetFiles("C:\Users\User\Desktop", "lalala.txt", IO.SearchOption.AllDirectories)
If ListBox1.SelectedIndex = -1 Then
MsgBox("No files selected")
Else
System.IO.File.Delete(ListBox1.Items(ListBox1.SelectedIndex).ToString())
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
End If
However, only the items in the listbox are deleted. The actual file still exists. I am unsure where I should put the file into the Delete function.
I have referred to this but it has not helped me.
________UPDATE________
I have discovered where it went wrong: it is because only the file name is added to the listbox:
ListBox1.Items.Add(Path.GetFileName(fileFound))
Instead of Path.GetFullPath.
Anyhow, can I delete the file with GetFileName only?
The problem, as you realised, is that the filename only is not enough information to delete a file. You need the whole path to the file as well. So you need some way of storing the whole path but only showing the filename. This is also important because there might be two (or more) files with same name in separate directories.
A ListBox can have its Datasource property set to show items from "an object that implements the IList or IListSource interfaces, such as a DataSet or an Array."
Then you set the DisplayMember and ValueMember properties to tell it what to display and what to give as the value.
For example, I made up a class named "FileItem" which has properties for the full filename and for whatever you want to display it as, filled a list with instances of "FileItem", and told ListBox1 to display it:
Imports System.IO
Public Class Form1
Class FileItem
Property FullName As String
Property DisplayedName As String
Public Sub New(filename As String)
Me.FullName = filename
Me.DisplayedName = Path.GetFileNameWithoutExtension(filename)
End Sub
End Class
Private Sub PopulateDeletionList(dir As String, filter As String)
Dim files = Directory.EnumerateFiles(dir, filter, SearchOption.AllDirectories)
Dim fileNames = files.Select(Function(s) New FileItem(s)).ToList()
Dim bs As New BindingSource With {.DataSource = fileNames}
ListBox1.DataSource = bs
ListBox1.DisplayMember = "DisplayedName"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_Click(sender As Object, e As EventArgs) Handles ListBox1.Click
Dim lb = DirectCast(sender, ListBox)
Dim sel = lb.SelectedIndex
If sel >= 0 Then
Dim fileToDelete = CStr(lb.SelectedValue)
Dim choice = MessageBox.Show("Do you really want to delete " & fileToDelete, "Confirm file delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If choice = DialogResult.Yes Then
Try
File.Delete(fileToDelete)
lb.DataSource.RemoveAt(sel)
Catch ex As Exception
MessageBox.Show("Could not delete " & fileToDelete & " because " & ex.Message)
End Try
End If
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PopulateDeletionList("C:\temp", "*.txt")
End Sub
End Class
Edited I had forgotten to delete the item from the ListBox. To do that, it needs to be tied to the DataSource through a BindingSource.
Extra feature Seeing as there could be more than one file with the same name, you might want to add a tooltip to the listbox items so that you can see which directory it is in. See how to add tooltips on winform list box items for an implementation which needs only minor adjustments to work, such as:
Dim toolTip As ToolTip = New ToolTip()
' ...
Private Sub ListBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseMove
Dim lb = DirectCast(sender, ListBox)
Dim index As Integer = lb.IndexFromPoint(e.Location)
If (index >= 0 AndAlso index < ListBox1.Items.Count) Then
Dim desiredTooltip = DirectCast(lb.Items(index), FileItem).FullName
If (toolTip.GetToolTip(lb) <> desiredTooltip) Then
toolTip.SetToolTip(lb, desiredTooltip)
End If
End If
End Sub
The most simple (and reliable) solution would be to create a custom data type and add that to the ListBox instead.
By overriding the ToString() method you can make it display only the file name, while the back-end object still contains the full path.
Public Structure FileEntry
Public FullPath As String 'A variable holding the full path to the file.
'Overriding the ToString() method, making it only return the file name.
Public Overrides Function ToString() As String
Return System.IO.Path.GetFileName(Me.FullPath)
End Function
Public Sub New(ByVal Path As String)
Me.FullPath = Path
End Sub
End Structure
Now whenever you want to add paths to the ListBox you've got to add a new instance of the FileEntry structure, instead of a regular string:
ListBox1.Items.Add(New FileEntry(fileFound))
And to delete you just cast the currently selected item into a FileEntry, and then pass its FullPath onto the File.Delete() method.
Dim Entry As FileEntry = DirectCast(ListBox1.Items(ListBox1.SelectedIndex), FileEntry)
System.IO.File.Delete(Entry.FullPath)
NOTE: For this to work every item in the list box must be a FileEntry.
Online test: https://dotnetfiddle.net/x2FuV3 (pardon the formatting, DotNetFiddle doesn't work very well on a cellphone)
Documentation:
How to: Declare a Structure (Visual Basic) - Microsoft Docs
Overriding the Object.ToString() method - MSDN
You can use Path.Combine.
Since you are going to search in C:\Users\User\Desktop, you can do this to delete:
System.IO.File.Delete(Path.COmbine("C:\Users\User\Desktop",ListBox1.Items(ListBox1.SelectedIndex).ToString())
Here, "C:\Users\User\Desktop" and the selected index's text will be combined to make a single path.
Edit:
I get it, you want to show the file name onlyy in the textbox but want to delete the file from the system too but can't do it, right?
Well you can do this:
Put two listbox and while you add a file to a listbox1, put it's path to the listbox2 whose visibility will be False, meaning it won't be shown in the runtime.
DOing this, while an item is selected in the listbox1, use the path.combine to make a path by adding the filename & path from the list with same index number.
Something like this:
System.IO.File.Delete(path.combine(ListBox1.Items(ListBox1.SelectedIndex).ToString(), ListBox2.Items(ListBox1.SelectedIndex).ToString())

How to auto fill a textbox from a comobobox using a textfile

I 'm currently creating a form in VB that uses a text file to gather information for a combo box then automatic use the next word in the text file that's comma delimited to automatically populate a textbox.
But the current code I wrote show the list for the combo box but always auto fills the textbox with the second word on the second line and will not change the textbox after i select another option from the combo box can someone help?
Sorry if this isn't very clear.
My Text file is in this format:
Robert,5 BellView Road
Martin,6 BellView Road
Ect....
My code is as follows:
Dim LineString As String
Dim FieldString As String()
Try
Dim ContactInfoStreamReader As StreamReader = New StreamReader("C:\temp\test1.txt")
Do Until ContactInfoStreamReader.Peek = -1
LineString = ContactInfoStreamReader.ReadLine()
FieldString = LineString.Split(CChar(","))
LineString = FieldString(0)
ComboBox1.Items.Add(LineString)
Loop
RichTextBox2.Text = FieldString(1)
ContactInfoStreamReader.Close()
Catch ex As Exception
MsgBox("""Customers Name & Address.txt"" file was not found")
End Try
Ok, I know you have provided code, however this is how I would do it.
First of all we make a Person Class and create a Person List to store each Person
After that we read / load the text file into a string array and then we use Linq to split the text files line where the comma is and have it sort the name and address into two keys one being NAME and the other being ADDRESS. Once that is done we loop through each of the items and create a new Person with the values value.NAME and Value.Address for the persons name and address as well as add the person's name into a comboboxand finally we add a ComboBox Event that changes the Textbox's text to the selected ComboBox's Index that matches the List of People that was created to store each Person
Public Class Form1
Dim People As New List(Of Person)
Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged
Try
TextBox1.Text = People(ComboBox1.SelectedIndex).address
Catch
''this will prevent errors if there is a name with no address
TextBox1.Text = ""
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
''This is the location I used, feel free to change it here.
Dim location As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim fileName As String = "test1.txt"
Dim path As String = System.IO.Path.Combine(location, fileName)
Dim query = From line In System.IO.File.ReadAllLines(path)
Let val = line.Split(",")
Select New With {Key .NAME = val(0), Key .ADDRESS = val(1)}
For Each value In query
Dim p = New Person(value.NAME, value.ADDRESS)
People.Add(p)
ComboBox1.Items.Add(value.NAME)
Next
''ADD OTHER COMBOBOX ITEMS HERE IF NEED BE, SO EVERYTHING IS IN ORDER
ComboBox1.Items.Add("ANDREW")
End Sub
End Class
Class Person
Public Property name() As String
Public Property address() As String
Public Sub New(name As String, address As String)
Me.name = name
Me.address = address
End Sub
End Class
EDIT:This is how I formatted the text file.Robert,5 BellView Road
Martin,6 BellView Road

Using a combo box to store items in an array from a text file and then using that array and its components in another form

I'm currently designing an application within visual basic using vb.net. The first form asks for login information and then prompts the next form to select a customer. The customer information is stored in a text file that gets put in an array. I next have a form for the user to display and edit that information. How can I use the array I already created in the previous form in my display and edit form?
Private Sub frmCustomerList_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sr As StreamReader = File.OpenText("customer.txt")
Dim strLine As String
Dim customerInfo() As String
Do While sr.Peek <> -1
strLine = sr.ReadLine
customerInfo = strLine.Split("|")
cboCustomers.Items.Add(customerInfo(0))
customerList(count) = strLine
count = count + 1
Loop
End Sub
Private Sub cboCustomers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCustomers.SelectedIndexChanged
Dim customerInfo() As String
Dim index As Integer = cboCustomers.SelectedIndex
Dim selectedCustomer As String = customerList(index)
customerInfo = selectedCustomer.Split("|")
End Sub
Make the next form require it in the constructor:
Public Class EditCustomer
Public Sub New(customerInfo As String())
InitializeComponent() 'This call is required, do not remove
'Yay! Now you have your info
End Sub
End Class
You'd call it by doing something like...
Dim editForm = New EditCustomerFrom(customerInfo)
editForm.Show()
Alternatively, you could have a property on the form you set.
Dim editForm = New EditCustomerFrom()
editForm.Customer = customerInfo
editForm.Show()
Then inside the Load event of that form, you'd write the logic that would display it looking at that property.
Aside: You should look at maybe defining an object to hold customer info and do some JSON or XML serialization for reading/writing to the file, IMO. This architecture is kind of not good as is....