Hello.

I want to know if someone can help me with this:

I'm starting to write some code to run an office (not professionally).
When I write the Client Class, how do I make it that the number of the client be a primary key (unique and auto incremental)?

Also, I want that all the Client and Products data be stored on a txt file.

Any thoughts?

Thank you in advance.

V

Hi!

you need to write your file in a proper manner to retrieve information back.

For Primary number, in a .txt file there is no way to create a column having type "Autonumber" you need to read the file and extract the max ID and when inserting increment the ID by 1.

To accomplish the task these link will help you:
http://www.emoreau.com/Entries/Articles/2010/05/Do-you-know-the-TextFieldParser.aspx

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx

Hello, ShahanDev. Thank you for your answer.

I'm trying to do this on Microsoft Visual Studio 2010, using VB.net. (I hope that's what you meant to know...).

Yes, I know of that resource on Access or SQL, but programming it on VB, I don't know how to do it. That«s one of the reasons for this thread.

If you want to store your data in text file then you need to use two the link I provided in the above post.

If you want to manage the data in SQL, or MSAccess you can use these namespaces:
System.Data.OleDB

Classes:
OleDBConnection
OleDBCommand
OleDBDataAdapter
OleDBDataReader
etc....

System.Data.SqlClient

Classes:
SqlConnection
SqlCommand
SqlDataAdapter
SqlDataReader
etc....

No, this is just for a VB solo project, no DB connections. A txt file will be more than enough. Thank you for the links, ShahanDev.

I will read them and I'll get back here with the results.

Cheers!

Ok, this works but only if you already have a file. I actually need that when you press the "Clients" button, the file is created with the data that I put in on the text boxes.

Another thing, I still don't understand the autoid incremental thing. Can I not put the number of the first client (that when we first start the application is 1) to the newly created text file and then read it from there? More importantly, how do I do it? :)

hi!

To create a file, article have this piece of code, which I amended for you

If Not IO.File.Exists(strFile) Then
        MessageBox.Show("File does not exist!", _
                        "File not found", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Error)
        Return
else
[B] 'CreateYourFile Here[/B]
    End If

>>>Another thing, I still don't understand the autoid incremental thing
You can store your maximum id in the file as well, you will see this line "--skip this line" in the article, so use that technique to store the maximum id allocated uptil now and assign the new id by incrementing it.

Again, thank you for your help, ShahanDev.

I understand that this can be quite annoying. The thing is that all these examples are supposed to read the txt file and display it on the screen as a string on a screen. What I want it to do is to take a line on the file (ex: id, name, address, phone) and put each of those on their respective text box on a form. I don't know if I made myself clear on this... if so, I apologize.

What I'm trying to do now is use this piece of code that I find, but I have a problem with the casting, I think. And also with the try...catch.

Public Sub LoadClients()
        Dim file As StreamReader
        Dim temp As String
        Try
            file = New StreamReader("Clients.csv")
            temp = file.ReadLine()
            While Not temp Is Nothing
                Dim ListTemp() As String = temp.Split(CChar(","))
                ClientBindingSource.Add(New Client(CInt(ListTemp(0)), ListTemp(1), ListTemp(2)))
                temp = file.ReadLine()
            End While
            file.Close()
        Catch ex As Exception
            WriteLine("ERROR!!! {0}", ex.Message)
            Return
        End Try
    End Sub

EDIT: the structure I have on the csv file is

1 Brian Street A 324234

Your line 9 should be like this:

Dim ListTemp() As String = temp.Split(CChar(" "))

i.e., instead of ',' use '<space>' because your text is <space> separated not "comma" separated.

Your line 9 should be like this:

Dim ListTemp() As String = temp.Split(CChar(" "))

i.e., instead of ',' use '<space>' because your text is <space> separated not "comma" separated.

I'm sorry, that was a mistake of my part. Now, I'm using a txt file and I have this code:

Public Sub LoadClients()
        Dim file As StreamReader
        Dim temp As String
    Try
        file = New StreamReader("Clients.txt")
        temp = file.ReadLine()
        While Not temp Is Nothing
             Dim ListTemp() As String = temp.Split(CChar(","))
            ClientBindingSource.Add(New Client(CInt(ListTemp(0)), ListTemp(1), ListTemp(2), CDbl(ListTemp(3))))
            temp = file.ReadLine()
        End While
        file.Close()
        
    Catch ex As Exception
            WriteLine("ERROR!!! {0}", ex.Message)
            Return
    End Try
End Sub

Being that the txt file is like this: 1,HANNA,Street 1,32432

Also, I have on the client class:

Public Class Client

    Public Property num As Integer
    Public Property name As String
    Public Property address As String
    Public Property phone As Double



    Public Sub New(ByVal num As Integer, ByVal name As String, ByVal address As String, ByVal phone As Double)
        Me.num = num
        Me.name = name
        Me.address = address
        Me.phone = phone
    End Sub

NOW IT WORKS!!!! :D

Thank you very much, ShahanDev. I will now try to work on the save to the file part. I'll get back to you with the results.

Uhmmm... can't get it to work.

I'm using this but it does nothing. I can read the file, but I can't alter them, delete or add.

Public Sub SaveClient()
            Dim file As StreamWriter
            Try
                file = New StreamWriter("Clients.csv")
            Catch ex As Exception
                WriteLine("Not possible to save file. {0}", ex.Message)
                Return
        End Try
        file.BaseStream.Seek(0, SeekOrigin.End)
        'the seek method is used to move the cursor to next position to avoid text to be
        'overwritten
        For Each c As Client In ListclientsBindingSource
            file.WriteLine(c.listClient())
        Next
            file.Close()
        End Sub

Is this a bindingSource "ListaclientesBindingSource"???

Is this a bindingSource "ListaclientesBindingSource"???

Yes, it is.

Stupid of me, this didn't work because I was using the csv file. Now, it adds and deletes records. It just doesn't let me change any of them. And I've still got to work out the num to be primary key....

EDIT: I can change only blank fields on records. Those that already have something on the field, I can't edit.

See if this helps.

New Project and No previous Clients.txt File.

'//------ Pre-requisites: 4 TextBoxes (ID/Name/Address/Phone)
'------------------------ 2 Buttons (Add Client/Clear Fields)
'------------------------ 1 ComboBox (Load Client Information) -------\\
Public Class Form1
    Private myClientsFile As String = "C:\Users\codeorder\Desktop\Clients.txt" '// your File to Load / Save.
    Private arlClients As New ArrayList '// keeps all Clients Information.
    Private iClientID As Integer = 1 '// ID #.

    '//--------- Save File. --------------\\
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim myWriter As New IO.StreamWriter(myClientsFile)
        For Each itm As String In arlClients '// Loop thru all Clients in the ArrayList.
            myWriter.WriteLine(itm) '// write each Client on a new line.
        Next
        myWriter.Close()
    End Sub

    '//--------- Load File if Exists. --------------\\
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If IO.File.Exists(myClientsFile) Then '// check if File Exists.
            arlClients.AddRange(IO.File.ReadAllLines(myClientsFile)) '// Load your Clients File in the ArrayList.
            Dim arTemp() As String = Nothing '// String Array to .Split the File Lines into Arrays.
            For Each itm As String In arlClients '// Loop thru all Clients that were added to the ArrayList.
                arTemp = itm.Split("~") '// .Split Line by your selected char.
                '// check if String Array 1 is greater than the last added ID, if so, change the iClientID.
                If CInt(arTemp(0)) > iClientID Then iClientID = CInt(arTemp(0))
                ComboBox1.Items.Add(arTemp(1)) '// add only Client Name to ComboBox.
            Next
            iClientID += 1 '// increase for Next available ID.
        Else '//-------- TESTING PURPOSES TO DETERMINE TEXTBOXES.
            TextBox2.Text = "name" : TextBox3.Text = "address" : TextBox4.Text = "phone" '------\\
        End If
        TextBox1.Text = iClientID '// add current ID #.
        ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList '// disable editing.
        '//-------- TESTING PURPOSES
        Button1.Text = "Add Client" : Button2.Text = "Clear All" '------\\
    End Sub

    '//--------- Add New Client. --------------\\
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '// store all Client Information into a String, separating each Field with your selected char.
        Dim sTemp As String = TextBox1.Text & "~" & TextBox2.Text & "~" & TextBox3.Text & "~" & TextBox4.Text
        '// Check if Client already exists.
        For Each itm As String In arlClients '// Loop thru Clients ArrayList.
            If itm = sTemp Then '// check if Client has already been added.
                MsgBox("Client Exists.", MsgBoxStyle.Information)
                Exit Sub '// Do Not run the rest of the code for Adding a Client.
            End If
        Next
        '// Add Client.
        arlClients.Add(sTemp) '// add all Client Information to ArrayList.
        ComboBox1.Items.Add(TextBox2.Text) '// add only Client name to ComboBox.
        iClientID += 1 '// increase ID #.
        TextBox1.Text = iClientID '// set new ID # for use.
        TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() '// Clear other TextBoxes.
        TextBox2.Select() '// preselect the Name TextBox for new Client.
    End Sub

    '//--------- Load Client Information into TextBoxes. --------------\\
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        If Not arlClients.Count - 1 < ComboBox1.SelectedIndex Then '// check if current Selected Client is in ArrayList.
            Try
                Dim arTemp() As String = arlClients(ComboBox1.SelectedIndex).ToString.Split("~") '// .Split all Client Information into String Arrays.
                '// Add Client Information to TextBoxes.
                TextBox1.Text = arTemp(0) : TextBox2.Text = arTemp(1) : TextBox3.Text = arTemp(2) : TextBox4.Text = arTemp(3)
            Catch ex As Exception
                MsgBox(ex.Message) '// if Client Information is not under correct format.
            End Try
        End If
    End Sub

    '//--------- Clear all Fields and set current available ID. --------------\\
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = iClientID '// set ID # for use.
        TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() '// Clear other TextBoxes.
    End Sub
End Class
commented: Very helpful. +1

You can not edit; until and unless, you moves your whole file into memory by either File.ReadAllLINES() or some other methods OR write the same/newfile by truncating/creating it. If your file is too long then it some time raises "OutOfMemoryException". So one way as a solution:

  • create a new file
  • find offset of that record by locating it in file.
  • write the preceding record(s) in a new file(the records present before this record)
  • save the records which has edited now.
  • write the remaining records
  • Delete previous written file.

I will try it. Thank you for your answers. I'll come back with the results in a few hours. Need to get some sleep now... ;)

See if this helps.

New Project and No previous Clients.txt File.

'//------ Pre-requisites: 4 TextBoxes (ID/Name/Address/Phone)
'------------------------ 2 Buttons (Add Client/Clear Fields)
'------------------------ 1 ComboBox (Load Client Information) -------\\
Public Class Form1
    Private myClientsFile As String = "C:\Users\codeorder\Desktop\Clients.txt" '// your File to Load / Save.
    Private arlClients As New ArrayList '// keeps all Clients Information.
    Private iClientID As Integer = 1 '// ID #.

    '//--------- Save File. --------------\\
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim myWriter As New IO.StreamWriter(myClientsFile)
        For Each itm As String In arlClients '// Loop thru all Clients in the ArrayList.
            myWriter.WriteLine(itm) '// write each Client on a new line.
        Next
        myWriter.Close()
    End Sub

    '//--------- Load File if Exists. --------------\\
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If IO.File.Exists(myClientsFile) Then '// check if File Exists.
            arlClients.AddRange(IO.File.ReadAllLines(myClientsFile)) '// Load your Clients File in the ArrayList.
            Dim arTemp() As String = Nothing '// String Array to .Split the File Lines into Arrays.
            For Each itm As String In arlClients '// Loop thru all Clients that were added to the ArrayList.
                arTemp = itm.Split("~") '// .Split Line by your selected char.
                '// check if String Array 1 is greater than the last added ID, if so, change the iClientID.
                If CInt(arTemp(0)) > iClientID Then iClientID = CInt(arTemp(0))
                ComboBox1.Items.Add(arTemp(1)) '// add only Client Name to ComboBox.
            Next
            iClientID += 1 '// increase for Next available ID.
        Else '//-------- TESTING PURPOSES TO DETERMINE TEXTBOXES.
            TextBox2.Text = "name" : TextBox3.Text = "address" : TextBox4.Text = "phone" '------\\
        End If
        TextBox1.Text = iClientID '// add current ID #.
        ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList '// disable editing.
        '//-------- TESTING PURPOSES
        Button1.Text = "Add Client" : Button2.Text = "Clear All" '------\\
    End Sub

    '//--------- Add New Client. --------------\\
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '// store all Client Information into a String, separating each Field with your selected char.
        Dim sTemp As String = TextBox1.Text & "~" & TextBox2.Text & "~" & TextBox3.Text & "~" & TextBox4.Text
        '// Check if Client already exists.
        For Each itm As String In arlClients '// Loop thru Clients ArrayList.
            If itm = sTemp Then '// check if Client has already been added.
                MsgBox("Client Exists.", MsgBoxStyle.Information)
                Exit Sub '// Do Not run the rest of the code for Adding a Client.
            End If
        Next
        '// Add Client.
        arlClients.Add(sTemp) '// add all Client Information to ArrayList.
        ComboBox1.Items.Add(TextBox2.Text) '// add only Client name to ComboBox.
        iClientID += 1 '// increase ID #.
        TextBox1.Text = iClientID '// set new ID # for use.
        TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() '// Clear other TextBoxes.
        TextBox2.Select() '// preselect the Name TextBox for new Client.
    End Sub

    '//--------- Load Client Information into TextBoxes. --------------\\
    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        If Not arlClients.Count - 1 < ComboBox1.SelectedIndex Then '// check if current Selected Client is in ArrayList.
            Try
                Dim arTemp() As String = arlClients(ComboBox1.SelectedIndex).ToString.Split("~") '// .Split all Client Information into String Arrays.
                '// Add Client Information to TextBoxes.
                TextBox1.Text = arTemp(0) : TextBox2.Text = arTemp(1) : TextBox3.Text = arTemp(2) : TextBox4.Text = arTemp(3)
            Catch ex As Exception
                MsgBox(ex.Message) '// if Client Information is not under correct format.
            End Try
        End If
    End Sub

    '//--------- Clear all Fields and set current available ID. --------------\\
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = iClientID '// set ID # for use.
        TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() '// Clear other TextBoxes.
    End Sub
End Class

Hello, codeorder. Thank you for your answer.

I've been looking at your code and, to be honest, I'm really not getting this to work because it writes to the file but when I close the application and then open it again, it doesn't load the data stored on it.

Also, can't this be done according to the logic I've been using with lists?

Or, at least can I "incorporate" this id into my code?

Once again, thank you for your answer.

You can not edit; until and unless, you moves your whole file into memory by either File.ReadAllLINES() or some other methods OR write the same/newfile by truncating/creating it. If your file is too long then it some time raises "OutOfMemoryException". So one way as a solution:

  • create a new file
  • find offset of that record by locating it in file.
  • write the preceding record(s) in a new file(the records present before this record)
  • save the records which has edited now.
  • write the remaining records
  • Delete previous written file.

Good morning, ShahanDev.

Once again, thank you for your help. I more or less understand the items on your list (except the offset part), but can you point me to an example or something? I have no clue how to do what you suggest.

Hello, codeorder. Thank you for your answer.

I've been looking at your code and, to be honest, I'm really not getting this to work because it writes to the file but when I close the application and then open it again, it doesn't load the data stored on it.

Also, can't this be done according to the logic I've been using with lists?

Or, at least can I "incorporate" this id into my code?

Once again, thank you for your answer.

If you want to load the data stored in the file when loading your application again with the code sample I have provided, simply select any Client from the ComboBox.

About having it "done according to the logic I've been using with lists" and/or ""incorporate" this id into my code", please post the entire code you have done so far, possibly with some comments.

I previously have tried to figure out how to provide a solution using your code examples, but due to your code constantly changing and only having bits and pieces of code here and there, I was not able to figure out what is what and how it all connects.

If you want to load the data stored in the file when loading your application again with the code sample I have provided, simply select any Client from the ComboBox.

About having it "done according to the logic I've been using with lists" and/or ""incorporate" this id into my code", please post the entire code you have done so far, possibly with some comments.

I previously have tried to figure out how to provide a solution using your code examples, but due to your code constantly changing and only having bits and pieces of code here and there, I was not able to figure out what is what and how it all connects.

codeorder, I understand that maybe what I'm asking is confusing. I appreciate you taking the time to helping me. Would it be ok that I put all the classes and forms on a zip file and post it here? If so, please bare in mind that the variables are written in Portuguese and I've been translating to English so that anyone can understand.

If you're still willing to take a look...

Cliente - Client
Modalidade - sport
Aula - one class where you do a sport
Turma - Class (of students)
Inscricao - something you have to pay to get in
Mensalidade - you pay that every month

I think that's it...

Thank you very much.

I downloaded the project, reviewed the files, and all that "non english" makes my head spin trying to figure out what is what.:(

Sorry, but I do not have a solution to provide. Good luck.

I downloaded the project, reviewed the files, and all that "non english" makes my head spin trying to figure out what is what.:(

Sorry, but I do not have a solution to provide. Good luck.

OK codeorder, fair enough. Thank you for your help. Have a good year.

Hello again to all. Hope you had a good New year.

Tell me one thing if you can: using the code that codeorder provided, is it possible to print the arrayList?

Thank you

Hello again to all. Hope you had a good New year.

Tell me one thing if you can: using the code that codeorder provided, is it possible to print the arrayList?

Thank you

OK, got it to work. Thank you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.