Avatar of Computer Guy
Computer Guy
 asked on

VB Help

Hi,

I have some data that is in a txt file. When the application loads, I will have the ability to add more data to the file. Though there is one field that can't be duplicated. So I need to check the existing records against the data I am going to enter.

When I'm in the application I have the lost_focus command on the field I want to check and I store the data into an array. So if I enter a duplicate employee number there will be an error.

The problem is when I open the application it won't check against existing data, just what I enter in now. Any ideas on how I can make this work? I know It's simple I just can't place it.

Lost Focus Code
    Private Sub txtEmployeeNumber_LostFocus(sender As Object, e As EventArgs) Handles txtEmployeeNumber.LostFocus
        'Check For Existing Employee Number
        Dim index As Integer = Array.IndexOf(empArray, CInt(txtEmployeeNumber.Text))
        If index = -1 Then
            ReDim Preserve empArray(empArray.Length)
            empArray(empArray.Length - 1) = CInt(txtEmployeeNumber.Text)
        Else
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        End If
    End Sub

Open in new window


Here is my code that writes to the file
            Try
                Dim strFirstName As String = txtFirstName.Text
                Dim strMiddleName As String = txtMiddleName.Text
                Dim strLastName As String = txtLastName.Text
                Dim intEmployeeNumber As Integer = CInt(txtEmployeeNumber.Text)
                Dim strDepartment As String = ComboBoxDepartment.SelectedItem.ToString()
                Dim strTelephone As String = txtPhoneNumber.Text
                Dim intExtension As Integer = CInt(txtExtension.Text)
                Dim strEmail As String = txtEmailAddress.Text
                Dim intBaseSalary As Integer = CInt(txtBaseSalary.Text)

                employeeFile = File.AppendText(strFileName)
                employeeFile.WriteLine(strFirstName)
                employeeFile.WriteLine(strMiddleName)
                employeeFile.WriteLine(strLastName)
                employeeFile.WriteLine(txtEmployeeNumber.Text)
                employeeFile.WriteLine(strDepartment)
                employeeFile.WriteLine(strTelephone)
                employeeFile.WriteLine(txtExtension.Text)
                employeeFile.WriteLine(strEmail)
                employeeFile.WriteLine(intBaseSalary)
                employeeFile.WriteLine()
                'Display Message Box When Data Is Entered, Then Clear For New Data
                MessageBox.Show("Data Entered Successfully")
                Clear_Stuff()
            Catch
                'Display Error If There Is A Problem With File (For Extra Measures)
                MessageBox.Show("File Can't Be Written To")
            End Try
        End If

Open in new window

Visual Basic.NET

Avatar of undefined
Last Comment
Computer Guy

8/22/2022 - Mon
John (Yiannis) Toutountzoglou

Hi...
The problem is when I open the application it won't check against existing data
You can use a StreamReader ..Search for a certain String and if this exist in the file add it to a list..
 Function ReadTextFileData(ByRef EmployeeNo As String) As IEnumerable(Of String)
        Dim result = New List(Of String)
        Using reader = New StreamReader("Myfile.txt")
            Dim line As String = reader.ReadLine()
            Dim Exist = False
            Do While line IsNot Nothing
                If line.StartsWith("'") Then
                    Exist = False
                End If
                If String.Equals("'" + EmployeeNo + "'", line) Then
                    Exist = True
                End If
                If Exist And Not String.IsNullOrEmpty(line) And Not line.StartsWith("'") Then
                    result.Add(line)
                End If
                line = reader.ReadLine()
            Loop
        End Using
        Return result
    End Function

Open in new window

So in your Event you can check...
Private Sub txtEmployeeNumber_LostFocus(sender As Object, e As EventArgs) Handles txtEmployeeNumber.LostFocus
        'Check For Existing Employee Number
        Dim FoundString as String =ReadTextFileData(Me.txtEmployeeNumber.Text)
            If Me.txtEmployeeNumber.text=FoundString
               'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else
           'Proceed
        End If
    End Sub

Open in new window

Computer Guy

ASKER
Hi, I have Options Strict on and got a little error

Run time errors might occur when converting to a string

I tried the code and it didn't generate an error

Also got a couple of exception errors when I enter a number and loose focus
Errors-when-I-lost-focus.jpg
Error-or-Warning.jpg
John (Yiannis) Toutountzoglou

Try this....
Private Sub txtEmployeeNumber_LostFocus(sender As Object, e As EventArgs) Handles txtEmployeeNumber.LostFocus
        'Check For Existing Employee Number
        Dim MyString As String = Me.txtEmployeeNumber.Text
        Dim FoundString As String = CStr((ReadTextFileData(MyString))(0))
        If Me.txtEmployeeNumber.text = FoundString Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else
            'Proceed
        End If
    End Sub

Open in new window

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Computer Guy

ASKER
Still does not show error if there is a duplicate

I get this every time I loose focus
A first chance exception of type 'System.InvalidCastException'
John (Yiannis) Toutountzoglou

Ok one more try before we testing another solution...
try to change
Function ReadTextFileData(ByRef EmployeeNo As String) As IEnumerable(Of String)

Open in new window

with
Function ReadTextFileData(ByRef EmployeeNo As String) As List(Of String)

Open in new window


and

Dim FoundString As String = CStr((ReadTextFileData(MyString))(0))

Open in new window

With
Dim FoundString As String = CStr((ReadTextFileData(MyString).Item(0)))

Open in new window


john...
Computer Guy

ASKER
Hrmm. I got this now A first chance exception of type 'System.ArgumentOutOfRangeException'
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

A different way ...
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'Check For Existing Employee Number
        Dim MyString As String = Me.txtEmployeeNumber.Text
        Dim text As String = File.ReadAllText("C:\Users\User\Desktop\Myfile.txt") 'your path here
        Dim index As Integer = text.IndexOf(MyString)
        If index >= 0 Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else
           MessageBox.Show("You may proceed") 
       End If
    End Sub

Open in new window

Computer Guy

ASKER
I'm interested in doing things this way:

Either Lost Focus

or

Form Loads, reads file, stores data in array, then compare on lost focus

I want to keep it somehow when you loose focus it will check instead of adding a button.
John (Yiannis) Toutountzoglou

do it in leave event .
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Computer Guy

ASKER
what do you mean?
John (Yiannis) Toutountzoglou

 Private Sub txtEmployeeNumber_Leave(sender As System.Object, e As System.EventArgs) Handles txtEmployeeNumber.Leave
        'Check For Existing Employee Number
        Dim MyString As String = Me.txtEmployeeNumber.Text
        Dim text As String = File.ReadAllText("C:\Users\User\Desktop\Myfile.txt")
        Dim index As Integer = text.IndexOf(MyString)
        If index >= 0 Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
           Exit Sub
        Else
           MessageBox.Show("You may proceed") 
        End If
    End Sub

Open in new window

John (Yiannis) Toutountzoglou

Did you try it?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Computer Guy

ASKER
Hi,

Sorry to bother you again. This is what I need to do, when the file opens, store all of the employee numbers in an array. The code you mentioned to me checks all of the data, so if I were to enter in a dollar amount, then it would still bring an error since that number is there.

So when the form loads, how can I store all of the employee numbers in an array?

This is how my data is stored in the file where 000x is the employee number

John
James
Doe
0001
Accounting
5555240001
0010
jdoe@domain.com
50000

John
James
Doe
0002
Marketing
5555240002
0020
jdoe@domain.com
75000

John
James
Doe
0003
Administration
5555240003
0030
jdoe@domain.com
90000
Computer Guy

ASKER
I have some array code as part of my original post.
John (Yiannis) Toutountzoglou

I provide you a solution now that read Line By line for a certain Value..
The structure of your file allows you to do to that...
This is just a check for a certain line...about storing this line in an array i will post you in a minute just try initialy this one..
in your lost Focus event
 'Check For Existing Employee Number
        Dim fileName As String = "C:\Users\User\Desktop\Myfile.txt"
        Dim someString As String = Me.txtEmployeeNumber.Text

        Dim lines As String() = File.ReadAllLines(fileName)
        Dim found As Boolean = False
        For i As Integer = 0 To lines.Length - 1
            If lines(i).Equals(someString) Then
                found = True
                Exit For
            End If
        Next
        If found Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else

        End If

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
John (Yiannis) Toutountzoglou

Hi this Works according to "your" Text File structure....
 Dim CodeList As List(Of String)
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        CodeList = New List(Of String)
        Dim fileName As String = "C:\Users\User\Desktop\Myfile.txt"
        Dim someString As String = Me.txtEmployeeNumber.Text

        Dim lines As String() = File.ReadAllLines(fileName)
        Dim found As Boolean = False
        For i As Integer = 3 To lines.Length - 1 Step 11
            CodeList.Add(lines(i))
            i -= 1
        Next
        For j As Integer = 0 To CodeList.Count - 1
            Console.WriteLine(CodeList(j))
        Next
    End Sub
    Private Sub txtEmployeeNumber_LostFocus(sender As Object, e As EventArgs) Handles txtEmployeeNumber.LostFocus
        Dim found As Boolean = False
        Dim someString = Me.txtEmployeeNumber.Text
        For i As Integer = 0 To CodeList.Count - 1
            If CodeList(i).Equals(someString) Then
                found = True
                Exit For
            End If
        Next
        If found Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else
            MessageBox.Show("You may Proceed")
        End If
    End Sub

Open in new window

Computer Guy

ASKER
Ok, cool Thanks :-)

Just a couple of general questions, and I can move some of this code around myself.

This will be a multi-part application and the part we were working on was a form the application.

I'm no the best with Stream Write and Read.

Can I open the file when the application opens, keep it open, use stream read/write functions throughout the entire application for different forms, etc, then upon exiting the main app, close the file?
John (Yiannis) Toutountzoglou

If i understand you Well...
I do not know how safe is that ..
The Sequence is
1.Create Or Load
2.Read
3.Close
If you need some contents of your file , add them to a List and use them everywhere...

John
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Computer Guy

ASKER
Lets create / load on application startup

The click on add records, and I want to be able to read the data like we have done and also write  new data to the file.

Then on another form I want to search for data

what do you recommend as far as opening and closing the file?
John (Yiannis) Toutountzoglou

This is exactly what StreamWriter and StreamReader do...
You do not have actualy to open the file..
Use  StreamWriter to Save/Write data or Append Text to your File
http://msdn.microsoft.com/en-us/library/system.io.fileinfo.appendtext.aspx
And use StreamReader to read the Contents of your File...

The only thing you have to do is to Close either the StreamReader or StreamWriter

Hope this is a guide...

Yiannis
Computer Guy

ASKER
Thanks. Should I open the file read/wrote and close it with each form event?

Can I read  and write with the same form
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
John (Yiannis) Toutountzoglou

yes you can ...Create a new instance at time ..
Just keep in mind to close the reader or the writer
Computer Guy

ASKER
Owhat do you mean by its own instance
John (Yiannis) Toutountzoglou

As the link says:
 Dim sw As StreamWriter

Then you can call
sw=new StreamWriter    <- this is a new instance of StreamWriter
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Mike Tomlinson

I highly recommend you get away from the file format you're using.  I would create a CLASS to hold each record and use an XmlSerializer to read/write the data.  You can store instances of that class in either a List or a Dictionary using the employee ID as the key.
Computer Guy

ASKER
So everywhere I use it in a form will be its own instance?  If I read and write 3 times it will be am instance
John (Yiannis) Toutountzoglou

Hi audioTech520
You can Read here
How to read and Write with Stream...
But Consider What Idle_Mind post you ....
I highly recommend you get away from the file format you're using

Believe me he knows Better than everyone..Unless this is just a personal app..

John....
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Computer Guy

ASKER
Haha ok. I normally don't play with VB., so I don't know what method is better than another.

Last question!

Out of my data, I need to be able to search for fields First Name, Last Name and Employee Number.

I have another form setup this way with the 3 text boxes and search. I'm taking it that I'll be using StreamReader with read all lines upon the click of a search or when I load the form, read the contents.

Since my fields are all over the place, what is the best way to designate spot 1 for First name, spot 3 for Last Name spot 4 for Employee number?. So if someone searches for John Doe then I can have a listcontrol? to display all of the data for him?

So have my text file formatted like this:

First Name
Middle Name
Last Name
Employee Number
Department
Phone Number
Extension
Email Address
Salary
BLANK LINE AS SPACE
then all over again.
John (Yiannis) Toutountzoglou

HI ...
You know already by the structure where a certain field like LastName is positioned..
So you can use
Dim line As String = File.ReadAllLines(fileName)(1)  '<-Middle name
Dim line As String = File.ReadAllLines(fileName)(2) '<- LastName

Open in new window


Hope it helps....
Computer Guy

ASKER
Something like this?

        Dim employeeFile As StreamReader
        Dim strFileName As String = "file.txt"

        Do While employeeFile.EndOfStream Not False

            Dim FirstName As String = File.ReadAllLines(strFileName)(0)
            Dim MiddleName As String = File.ReadAllLines(strFileName)(1)
            Dim LastName As String = File.ReadAllLines(strFileName)(2)
            Dim EmpNum As String = File.ReadAllLines(strFileName)(3)
            Dim Dept As String = File.ReadAllLines(strFileName)(4)
            Dim Phone As String = File.ReadAllLines(strFileName)(5)
            Dim Extension As String = File.ReadAllLines(strFileName)(6)
            Dim Email As String = File.ReadAllLines(strFileName)(7)
            Dim Salary As String = File.ReadAllLines(strFileName)(8)
            Dim Spacer As String = File.ReadAllLines(strFileName)(9)
            End Do
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

this might work for your structure....
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim fileName As String = "C:\Users\User\Desktop\Myfile.txt"
        If Me.txtEmployeeNumber.Text = "" Then
            Me.txtEmployeeNumber.Focus()
            Exit Sub
        ElseIf Not File.ReadAllLines(fileName).Any(Function(f) f = Me.txtEmployeeNumber.Text) Then
            MessageBox.Show("No Data Found")
            Me.txtEmployeeNumber.Text = ""
            Me.txtEmployeeNumber.Focus()
            Exit Sub
        Else
            Dim j As Integer = 0
            Dim SearchIndex As Integer = Nothing
            Dim indexesOfEmptyLines As New List(Of Integer)

            Dim someString As String = Me.txtEmployeeNumber.Text
            Dim lines As String() = File.ReadAllLines(fileName)
            Dim FinalSection As Integer = Nothing

            'Find the search Index
            For l As Integer = 0 To lines.Count - 1
                If lines(l).Equals(someString) Then
                    SearchIndex = l
                End If
            Next

            'count the empty lines
            For i As Integer = 0 To File.ReadAllLines(fileName).Count - 1
                If lines(i) = String.Empty Then
                    j += 1
                    indexesOfEmptyLines.Add(i)
                End If
            Next

            'search ...
            Dim NoEmptyLines As Integer = (File.ReadAllLines(fileName).Count - 1) - j
            Dim Sections As Integer = CInt(NoEmptyLines / 9)
            Dim SectionsList(Sections) As Dictionary(Of Integer, String)



            For i As Integer = 0 To Sections - 1
                SectionsList(i + 1) = New Dictionary(Of Integer, String)
                For x As Integer = 0 + (i * 10) To 8 + (i * 10)
                    SectionsList(i + 1).Add(x, lines(x))
                Next
            Next
            For d As Integer = 0 To Sections - 1
                If SectionsList(d + 1).ContainsKey(CInt(SearchIndex)) Then
                    FinalSection = d + 1
                    Dim FirstName As String = SectionsList(FinalSection).Item(0 + (d * 10)) : Me.TextBox1.Text = FirstName
                    Dim MiddleName As String = SectionsList(FinalSection).Item(1 + (d * 10)) : Me.TextBox2.Text = MiddleName
                    Dim LastName As String = SectionsList(FinalSection).Item(2 + (d * 10)) : Me.TextBox3.Text = LastName
                    Dim EmpNum As String = SectionsList(FinalSection).Item(3 + (d * 10)) : Me.TextBox4.Text = EmpNum
                    Dim Dept As String = SectionsList(FinalSection).Item(4 + (d * 10)) : Me.TextBox5.Text = Dept
                    Dim Phone As String = SectionsList(FinalSection).Item(5 + (d * 10)) : Me.TextBox6.Text = Phone
                    Dim Extension As String = SectionsList(FinalSection).Item(6 + (d * 10)) : Me.TextBox7.Text = Extension
                    Dim Email As String = SectionsList(FinalSection).Item(7 + (d * 10)) : Me.TextBox8.Text = Email
                    Dim Salary As String = SectionsList(FinalSection).Item(8 + (d * 10)) : Me.TextBox9.Text = Salary
                    Exit For
                End If
            Next
        End If
    End Sub

Open in new window


Hope it helps...
Computer Guy

ASKER
Hrmm. This is my search screen. Still having issues.
Search.jpg
John (Yiannis) Toutountzoglou

The Code I gave you Populates Every Details  for each Id ..
Also note that you can perform search with every field....
Try it to see that the code works..
Put a textbox for every field...
Then if you insist i will adjust for you ...

john
Your help has saved me hundreds of hours of internet surfing.
fblack61
Computer Guy

ASKER
Well, what does this part do? I only need to search from 3 text boxes

                    Dim FirstName As String = SectionsList(FinalSection).Item(0 + (d * 10)) : Me.TextBox1.Text = FirstName
                    Dim MiddleName As String = SectionsList(FinalSection).Item(1 + (d * 10)) : Me.TextBox2.Text = MiddleName
                    Dim LastName As String = SectionsList(FinalSection).Item(2 + (d * 10)) : Me.TextBox3.Text = LastName
                    Dim EmpNum As String = SectionsList(FinalSection).Item(3 + (d * 10)) : Me.TextBox4.Text = EmpNum
                    Dim Dept As String = SectionsList(FinalSection).Item(4 + (d * 10)) : Me.TextBox5.Text = Dept
                    Dim Phone As String = SectionsList(FinalSection).Item(5 + (d * 10)) : Me.TextBox6.Text = Phone
                    Dim Extension As String = SectionsList(FinalSection).Item(6 + (d * 10)) : Me.TextBox7.Text = Extension
                    Dim Email As String = SectionsList(FinalSection).Item(7 + (d * 10)) : Me.TextBox8.Text = Email
                    Dim Salary As String = SectionsList(FinalSection).Item(8 + (d * 10)) : Me.TextBox9.Text = Salary
John (Yiannis) Toutountzoglou

Search 1Search 2
You are clear i will adjust for 3 fields search but take a look ...

john...
I will sent you code in about 1 hour...

John
Computer Guy

ASKER
Is it best for me to display the search in something other than a text box? What if the person searches the last name smith and there are 3 entries?

Should I use a List Box? or something else that will display and format the text?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

in the code i post if there are duplicates you will just see the first found..
OPTIONS
1.Or  use for searchg something that returns unique results...Or
2.Make you life easier using an xml File..
You can manipulate data easily without using large pieces of code...
The only think you have to do is to declare Datacolumns. ....and you are ready...
Make a search on how to create an XML file..you will see that you need just 3 lines
It is not difficult but very complicated to search in a text file...

John...
Mike Tomlinson

"Is it best for me to display the search in something other than a text box? What if the person searches the last name smith and there are 3 entries?"

Look at the DataGridView control...
Computer Guy

ASKER
Hey John, Whats your code example?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
John (Yiannis) Toutountzoglou

Code Example about what about an XML..
do you want to create you an Xml File with The same Structure?
Computer Guy

ASKER
For reading the text file on load and displaying in a data grid upon search
John (Yiannis) Toutountzoglou

All items from The Text file are added to a list...
To set List as a datasource to a DatagridView
add this Class to your Form1 Class
Public Class EmployeColumns

        Public Sub New(ByVal FirstName As String, ByVal MiddleName As String, ByVal LastName As String, _
                       ByVal EmployeeNumber As String, ByVal Department As String, ByVal PhoneNumber As String, _
                       ByVal Extension As String, ByVal EmailAddress As String, ByVal Salary As String)
            _FirstName = FisrtName
            _MiddleName = MiddleName
            _LastName = LastName
            _EmployeeNumber = EmployeeNumber
            _Department = Department
            _PhoneNumber = PhoneNumber
            _Extension = Extension
            _EmailAddress = EmailAddress
            _Salary = Salary
        End Sub

        Private _FirstName As String
        Public Property FisrtName() As String
            Get
                Return _FirstName
            End Get
            Set(ByVal value As String)
                _FirstName = value
            End Set
        End Property

        Private _MiddleName As String
        Public Property MiddleName() As String
            Get
                Return _MiddleName
            End Get
            Set(ByVal value As String)
                _MiddleName = value
            End Set
        End Property
        Private _LastName As String
        Public Property LastName() As String
            Get
                Return _LastName
            End Get
            Set(ByVal value As String)
                _LastName = value
            End Set
        End Property
        Private _EmployeeNumber As String
        Public Property EmployeeNumber() As String
            Get
                Return _EmployeeNumber
            End Get
            Set(ByVal value As String)
                _EmployeeNumber = value
            End Set
        End Property
        Private _Department As String
        Public Property Department() As String
            Get
                Return _Department
            End Get
            Set(ByVal value As String)
                _Department = value
            End Set
        End Property
        Private _PhoneNumber As String
        Public Property PhoneNumber() As String
            Get
                Return _PhoneNumber
            End Get
            Set(ByVal value As String)
                _PhoneNumber = value
            End Set
        End Property
        Private _Extension As String
        Public Property Extension() As String
            Get
                Return _Extension
            End Get
            Set(ByVal value As String)
                _Extension = value
            End Set
        End Property
        Private _EmailAddress As String
        Public Property EmailAddress() As String
            Get
                Return _EmailAddress
            End Get
            Set(ByVal value As String)
                _EmailAddress = value
            End Set
        End Property
        Private _Salary As String
        Public Property Salary() As String
            Get
                Return _Salary
            End Get
            Set(ByVal value As String)
                _Salary = value
            End Set
        End Property
    End Class

Open in new window

Then In Form Load
 Dim fileName As String = "C:\Users\User\Desktop\Myfile.txt"
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim j As Integer = 0
        Dim indexesOfEmptyLines As New List(Of Integer)


        Dim lines As String() = File.ReadAllLines(fileName)

        
        For i As Integer = 0 To File.ReadAllLines(fileName).Count - 1
            If lines(i) = String.Empty Then
                j += 1
                indexesOfEmptyLines.Add(i)
            End If
        Next


        Dim NoEmptyLines As Integer = (File.ReadAllLines(fileName).Count - 1) - j
        Dim Sections As Integer = CInt(NoEmptyLines / 9)
        Dim SectionsList(Sections) As List(Of String)


        Dim list = New List(Of EmployeColumns)
        For i As Integer = 0 To Sections - 1
            SectionsList(i + 1) = New List(Of String)
            For x As Integer = 0 + (i * 10) To 8 + (i * 10)
                SectionsList(i + 1).Add(lines(x))

            Next
            list.Add(New EmployeColumns(SectionsList(i + 1).Item(0), SectionsList(i + 1).Item(1), SectionsList(i + 1).Item(2), SectionsList(i + 1).Item(3), _
                                            SectionsList(i + 1).Item(4), SectionsList(i + 1).Item(5), SectionsList(i + 1).Item(6), SectionsList(i + 1).Item(7), SectionsList(i + 1).Item(8)))
        Next


        Me.DataGridView1.DataSource = list
    End Sub

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

Easier way.....Less complicated...
Dim fileName As String = "C:\Users\User\Desktop\Myfile.txt"
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim j As Integer = 0
        Dim lines As String() = File.ReadAllLines(fileName)
        'count the empty lines
        For i As Integer = 0 To lines.Count - 1
            If lines(i) = String.Empty Then
                j += 1
            End If
        Next
        Dim NoEmptyLines As Integer = (File.ReadAllLines(fileName).Count - 1) - j
        'find the sections
        Dim Sections As Integer = CInt(NoEmptyLines / 9)
        'Create the Columns
        Me.DataGridView1.ColumnCount = 9
        Me.DataGridView1.Columns(0).Name = "First Name"
        Me.DataGridView1.Columns(1).Name = "Middle Name"
        Me.DataGridView1.Columns(2).Name = "Lastname Name"
        Me.DataGridView1.Columns(3).Name = "Employee Number"
        Me.DataGridView1.Columns(4).Name = "Department"
        Me.DataGridView1.Columns(5).Name = "Phone Number"
        Me.DataGridView1.Columns(6).Name = "Extension"
        Me.DataGridView1.Columns(7).Name = "Email Address"
        Me.DataGridView1.Columns(8).Name = "Salary"


        'add empty rows to datagridview
        For i As Integer = 1 To Sections
            Me.DataGridView1.Rows.Add()
        Next
        'Finally sent the value to cells
        Dim SectionsList(Sections) As List(Of String)
        For i As Integer = 0 To Sections - 1
            SectionsList(i + 1) = New List(Of String)
            For x As Integer = 0 + (i * 10) To 8 + (i * 10)
                SectionsList(i + 1).Add(lines(x))
            Next
            For k = 0 To SectionsList(i + 1).Count - 1
                Me.DataGridView1.Rows(i).Cells(k).Value = SectionsList(i + 1).Item(k)
            Next
        Next
    End Sub

Open in new window



john
Computer Guy

ASKER
Hi,

So use the second post you had of code for load. Then for the first part how do I associate the datagrid with the list??
John (Yiannis) Toutountzoglou

i post both solutions ...did not understand what you are saying..
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Computer Guy

ASKER
Ok, the second solution for Form Load, it will copy all of the data in the form upon load.

I want to do this so when I click btnSearch it will take the data from FirstName, Last Name or Employee ID, or all 3, search file for it  and populate the datagrid with results
ASKER CERTIFIED SOLUTION
John (Yiannis) Toutountzoglou

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Computer Guy

ASKER
Thanks :-)
Computer Guy

ASKER
Hi,

I think I have a little mistake here, when the file opens up, it will check the existing records, but when I add one that is unique I also need to add it to the list upon write so If someone were to add it again (in that session) it would go through:

How can I modify this?

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'Read File And Store Employee Numbers
        empNumList = New List(Of String)
        Dim strfileName As String = "text.txt"
        Dim empNum As String = txtEmployeeNumber.Text

        Dim Lines As String() = File.ReadAllLines(strFileName)
        'Dim Found As Boolean = False
        For i As Integer = 3 To Lines.Length - 1 Step 11
            empNumList.Add(Lines(i))
            i -= 1
        Next
        For j As Integer = 0 To empNumList.Count - 1
            Console.WriteLine(empNumList(j))
        Next
    End Sub    
	
	Private Sub txtEmployeeNumber_LostFocus(sender As Object, e As EventArgs) Handles txtEmployeeNumber.LostFocus
        'Check For Duplicate Employee Numbers
        Dim Found As Boolean = False
        Dim empNum = txtEmployeeNumber.Text
        For i As Integer = 0 To empNumList.Count - 1
            If empNumList(i).Equals(empNum) Then
                found = True
                Exit For
            End If
        Next
        If Found Then
            'Show Error If Dupicate
            MessageBox.Show("Employee Id Already Entered" & vbCrLf & _
                                "Please Enter A Unique Employee Number")
            txtEmployeeNumber.Text = ""
            txtEmployeeNumber.Focus()
        Else
        End If
    End Sub
	
	           
  Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
      
                'Will Append To Current File Instead Of Create It From Scratch Again
                employeeFile = File.AppendText(strFileName)
                employeeFile.WriteLine(strFirstName)
                employeeFile.WriteLine(strMiddleName)
                employeeFile.WriteLine(strLastName)
                employeeFile.WriteLine(txtEmployeeNumber.Text)
                employeeFile.WriteLine(strDepartment)
                employeeFile.WriteLine(strTelephone)
                employeeFile.WriteLine(txtExtension.Text)
                employeeFile.WriteLine(strEmail)
                employeeFile.WriteLine(intBaseSalary)
                employeeFile.WriteLine()
                'File Will Close After Every Added Record
                employeeFile.Close()
                'Display Message Box When Data Is Entered, Then Clear For New Data
                MessageBox.Show("Data Entered Successfully")
                Clear_Stuff()
            Catch
                'Display Error If There Is A Problem With File (For Extra Measures)
                MessageBox.Show("File Can't Be Written To")
            End Try
        End If
		End Sub

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
John (Yiannis) Toutountzoglou

So you need to "refresh" the list if i understand!!??
Computer Guy

ASKER
Yes
John (Yiannis) Toutountzoglou

in half an hour i wiil be back...with the code...computer is on daughters hands...
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Computer Guy

ASKER
Haha ok
John (Yiannis) Toutountzoglou

try
 Private Sub Populate()
        Me.DataGridView1.Rows.Clear()
        Dim j As Integer = 0
        Dim lines As String() = File.ReadAllLines(fileName)
        'count the empty lines
        For i As Integer = 0 To lines.Count - 1
            If lines(i) = String.Empty Then
                j += 1
            End If
        Next
        Dim NoEmptyLines As Integer = (File.ReadAllLines(fileName).Count - 1) - j
        'find the sections
        Dim Sections As Integer = CInt(NoEmptyLines / 9)
        'Create the Columns
        Me.DataGridView1.ColumnCount = 9
        Me.DataGridView1.Columns(0).Name = "First Name"
        Me.DataGridView1.Columns(1).Name = "Middle Name"
        Me.DataGridView1.Columns(2).Name = "Lastname"
        Me.DataGridView1.Columns(3).Name = "Employee Number"
        Me.DataGridView1.Columns(4).Name = "Department"
        Me.DataGridView1.Columns(5).Name = "Phone Number"
        Me.DataGridView1.Columns(6).Name = "Extension"
        Me.DataGridView1.Columns(7).Name = "Email Address"
        Me.DataGridView1.Columns(8).Name = "Salary"


        'add empty rows to datagridview
        For i As Integer = 1 To Sections
            Me.DataGridView1.Rows.Add()
        Next
        'Finally sent the value to cells
        Dim SectionsList(Sections) As List(Of String)
        For i As Integer = 0 To Sections - 1
            SectionsList(i + 1) = New List(Of String)
            For x As Integer = 0 + (i * 10) To 8 + (i * 10)
                SectionsList(i + 1).Add(lines(x))
            Next
            For k = 0 To SectionsList(i + 1).Count - 1
                Me.DataGridView1.Rows(i).Cells(k).Value = SectionsList(i + 1).Item(k)
            Next
        Next
        dtDgv = New DataTable
        dtDgv = DataGridViewToDataTable(Me.DataGridView1)
    End Sub

Open in new window

Then call the populate after save like:
 Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Try
            Dim employeeFile As StreamWriter
            'Will Append To Current File Instead Of Create It From Scratch Again
            employeeFile = File.AppendText(fileName)

            employeeFile.WriteLine(strFirstName.Text)
            employeeFile.WriteLine(strMiddleName.Text)
            employeeFile.WriteLine(strLastName.Text)
            employeeFile.WriteLine(txtEmployeeNumber.Text)
            employeeFile.WriteLine(strDepartment.Text)
            employeeFile.WriteLine(strTelephone.Text)
            employeeFile.WriteLine(txtExtension.Text)
            employeeFile.WriteLine(strEmailtxt.Text)
            employeeFile.WriteLine(intBaseSalary.Text)
            employeeFile.WriteLine()
            'File Will Close After Every Added Record
            employeeFile.Close()
            'Display Message Box When Data Is Entered, Then Clear For New Data
            MessageBox.Show("Data Entered Successfully")
            Populate()
        Catch
            'Display Error If There Is A Problem With File (For Extra Measures)
            MessageBox.Show("File Can't Be Written To")
        End Try
    End Sub

Open in new window

Computer Guy

ASKER
Hi,

I am sorry for the confustion. There were 2 parts to this post. Add form which I started off with and then search form.

So this was going to be for the add records. The code I lastly posted was for adding a record, when the form loads it will load all of the employee numbers.

Say employee numbers 1,2,3,4,5 are in the file.

Then I try to add 5, it would call an error. But if I add 6, it goes right in since it is not there. The problem is when I don't leave the form and add 6 again. It will go in since It's not part of the list. When I write the record to the file, I want to have something that will also add the txtEmployeeNumber.text to the empNum list that is in the load part. So if I were to add 6 in again, there would be an error.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Computer Guy

ASKER
I don't want to use the data grid though
John (Yiannis) Toutountzoglou

You asked for the datagridview...
For reading the text file on load and displaying in a data grid upon search


I you read again all the posts you will find a that somewhere we are checking for existing employe number..So before save in a the BtnSave Click perform this check and if exists exit the sub otherwise continue...


For other questions you may open another thread (question ) and aks whatever you want ..
I will be here....!!!
John
Computer Guy

ASKER
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy