Link to home
Start Free TrialLog in
Avatar of aplelois
aplelois

asked on

problem with edit button

hello,
the edit button is not editing my data from the ini file correctly.
when you click on the edit buttom from main.vb you go there
and then you see in the textbox with the data ID and Name.
when you save its makes a new line in the .ini file and
thats the problem

ini file is like this
ID_Here;Name_Here

code

Public Class frmEdit

    Private Sub cmdCancel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancel.Click
        frmMain.Enabled = True
        frmMain.Activate()
        Me.Close()
    End Sub

    Public Sub Populate(ByVal Record As Integer)
        On Error Resume Next
        Dim FileNo As Integer
        Dim strLine As String = ""
        FileNo = FreeFile
        FileOpen(FileNo, "C:\Accounts.ini", OpenMode.Input)
        Dim intRecord As Integer
        For intRecord = 0 To Record
            strLine = LineInput(FileNo)
        Next
        txtID.Text = Split(strLine, ";")(0)
        txtName.Text = Split(strLine, ";")(1)
        FileClose(FileNo)

    End Sub

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
        Dim FileNo As Short
        On Error Resume Next

        FileNo = FreeFile()
        FileOpen(FileNo, "C:\Accounts.ini", OpenMode.Append, , OpenShare.Shared)
        PrintLine(FileNo, txtID.Text & ";" & txtName.Text)
        FileClose(FileNo)

        frmMain.Enabled = True
        frmMain.Activate()
        Me.Close()
    End Sub
End Class
Avatar of MageDribble
MageDribble

the problem is in your fileopen call

    FileOpen(FileNo, "C:\Accounts.ini", OpenMode.Append, , OpenShare.Shared)

this will append (add) a new line to the end of your file.  What you want to do is open it for reading, find the line that needs to be changed then overwrite that data.
Avatar of aplelois

ASKER

ok, how do I do that ?
easiest way is to read the entire ini file into a string using filestream.  Alter the data you need to change.  Overwrite the original file with the string.
i'm not an expert of VB sorry but can you show me how to do it?
Avatar of Bob Learned
Imports System.IO

...


Dim reader As New StreamReader(fileName)
Dim fileText As String = reader.ReadToEnd()
Dim writer As New StreamWriter(fileName)
writer.Write(fileText.Replace("This text", "That text")
writer.Close()
reader.Close()

Bob
Hi aplelois;

See if this works for you.

    Private Sub cmdSave_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click

        ' Open file for reading
        Dim sr As New StreamReader("C:\Accounts.ini")
        ' Get all the info from the file
        Dim input As String = sr.ReadToEnd()
        sr.Close()
        ' Set to true when record found
        Dim FoundRec As Boolean = False
        ' Replace all CrLf with a | character
        input = Regex.Replace(input, "(\r\n)", "|")
        Dim Lines() As String = input.Split("|")
        ' Used to access the arrPersons
        Dim idx As Integer
        ' Find the record to edit
        For idx = 0 To Lines.Length - 1
            Dim editline As String = Lines(idx)
            If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then
                ' Record was found. Replace the data with new data
                Lines(idx) = txtID.Text.Trim & ";" & txtFirst.Text.Trim & ";" & _
                    txtLast.Text.Trim & ";" & txtEmail.Text.Trim & ";" & _
                    txtPhone.Text.Trim
                FoundRec = True
                Exit For
            End If
        Next
        ' If a modification was found write it out to INI file
        If FoundRec Then
            Dim sw As New StreamWriter("C:\Accounts.ini", False)
            input = String.Join(ControlChars.CrLf, Lines)
            sw.WriteLine(input)
            sw.Close()

            ' Get the record from the arrPersons ArrayList
            Dim p As frmMain.Persons = CType(frmMain.arrPersons(idx), frmMain.Persons)
            p.first = txtFirst.Text.Trim
            p.last = txtLast.Text.Trim
            p.email = txtEmail.Text.Trim
            p.phone = txtPhone.Text.Trim
            ' Update the ArrayList
            frmMain.arrPersons.Item(idx) = p
            ' Refresh the ListBox
            frmMain.lstAccounts.BeginUpdate()
            frmMain.lstAccounts.DataSource = Nothing
            frmMain.lstAccounts.Items.Clear()
            frmMain.lstAccounts.DisplayMember = "first"
            frmMain.lstAccounts.DataSource = frmMain.arrPersons
            frmMain.lstAccounts.EndUpdate()

        End If


        frmMain.Enabled = True
        frmMain.Activate()
        Me.Close()

    End Sub

Fernando
Error      3      Type 'StreamWriter' is not defined.
Error      2      Name 'Regex' is not declared.
Error      4      'Populate' is not a member of 'Browser.frmEdit'.
Only.
Error     3     Type 'StreamWriter' is not defined.
Error     2     Name 'Regex' is not declared.
I added these two lines now I dont get errors
Imports System.IO
Imports System.Text.RegularExpressions

now I get this error
{"Length cannot be less than zero. Parameter name: length"}

whats this for
If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then
my original code is, sorry for the confusion!

        Next
        txtName.Text = Split(strLine, ";")(0)
        txtLast.Text = Split(strLine, ";")(1)
        txtPhone.Text = Split(strLine, ";")(2)
        FileClose(FileNo)

    End Sub

----
        FileNo = FreeFile()
        FileOpen(FileNo, "C:\Accounts.ini", OpenMode.Append, , OpenShare.Shared)
        PrintLine(FileNo, txtName.Text & ";" & txtLast.Text & ";" & txtPhone.Text)
        FileClose(FileNo)
Hi aplelois;

Glad you found the needed Imports statements.

To your question: "whats this for"
If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then

Answer:
If you are editing the info in the Accounts.ini file that means you are updating a record and not adding a record. We need to find the record to be updated and update the fields. The editline is the current in the Accounts.ini file being looked at. The Substring(0, editline.IndexOf(";")) picks the part of the string starting at position 0 and ending at the first ";" which should be the ID that matches the txtID.Text text box for the record to be edited. The .Trim remove any spaces before and after the string.

To your question: "now I get this error"
{"Length cannot be less than zero. Parameter name: length"}

Answer:
Need to know on what line you are getting this error on.

To your last post, Date: 05/02/2006 04:02AM PDT, I am not sure what your question is.

Fernando
here
If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then

{"Length cannot be less than zero. Parameter name: length"}
Hi aplelois;

The most likely cause of this is that there is a blank line in the Accounts.ini or the split has placed a blank line into the Lines aray. You can add the If Not editline = "" Then statement as shown below to bypass blank lines.

            Dim editline As String = Lines(idx)
            If Not editline = "" Then
                If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then
                    ' Record was found. Replace the data with new data
                    Lines(idx) = txtID.Text.Trim & ";" & txtFirst.Text.Trim & ";" & _
                        txtLast.Text.Trim & ";" & txtEmail.Text.Trim & ";" & _
                        txtPhone.Text.Trim
                    FoundRec = True
                    Exit For
                End If
            End If

Fernando
Error      1      Variable 'editline' hides a variable in an enclosing block.


                ' Find the record to edit
                   For idx = 0 To Lines.Length - 1
 error           Dim editline As String = Lines(idx)
                     If editline = "" Then
                      Dim editline As String = Lines(idx)
                       If Not editline = "" Then
                        If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then
                         ' Record was found. Replace the data with new data
                          Lines(idx) = txtName.Text.Trim & ";" & txtLast.Text.Trim & ";" & txtPhone.Text.Trim
                         FoundRec = True
                        Exit For
                    End If
                End If
            End If
I dont have anything txtID
everytime I edit a record it make a new line to the .ini file
Hi aplelois;

This is the code you posted above at Date: 05/02/2006 06:17AM PDT. But this is not what I gave you. You do not need the Lines I marked.

                ' Find the record to edit
                   For idx = 0 To Lines.Length - 1

'==Do Not Need ===============================
error           Dim editline As String = Lines(idx)
                     If editline = "" Then
'========================================

                      Dim editline As String = Lines(idx)
                       If Not editline = "" Then
                        If editline.Substring(0, editline.IndexOf(";")).Trim = txtID.Text.Trim Then
                         ' Record was found. Replace the data with new data
                          Lines(idx) = txtName.Text.Trim & ";" & txtLast.Text.Trim & ";" & txtPhone.Text.Trim
                         FoundRec = True
                        Exit For
                    End If
                End If

'==Do Not Need ===============================
            End If
'==========================================

Now a couple of questions back I answered a question and you stated the format of the Accounts.ini file. Which if memory serves me right it was:

ID;First Name;Last Name;Email Address;Phone Number

Now to modify any given part of a line you must replace the whole line and not just the part that changes. So when you state in the following post, "I dont have anything txtID", How did you find the record you want to modify? This is why in my post which give the solution I had all the fields of the line and replace the old info in Lines array.

To the last post you had posted, if you coded it some what as I gave you then the whole file would have been re-written and therefore not added.

Fernando
sorry, is not working and is adding a blank line at the end

my ini file is
Name;Last;Phone

My whole code

Imports System.IO
Imports System.Text.RegularExpressions

Public Class frmEdit

    Private Sub cmdCancel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancel.Click
        frmMain.Enabled = True
        frmMain.Activate()
        Me.Close()
    End Sub

    Public Sub Populate(ByVal Record As Integer)
        On Error Resume Next
        Dim FileNo As Integer
        Dim strLine As String = ""
        FileNo = FreeFile
        FileOpen(FileNo, "C:\Accounts.ini", OpenMode.Input)
        Dim intRecord As Integer
        For intRecord = 0 To Record
            strLine = LineInput(FileNo)
        Next
        txtName.Text = Split(strLine, ";")(0)
        txtLast.Text = Split(strLine, ";")(1)
        txtPhone.Text = Split(strLine, ";")(2)
        FileClose(FileNo)

    End Sub

    Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click

        ' Open file for reading
        Dim sr As New StreamReader("C:\Accounts.ini")
        ' Get all the info from the file
        Dim input As String = sr.ReadToEnd()
        sr.Close()
        ' Set to true when record found
        Dim FoundRec As Boolean = False
        ' Replace all CrLf with a | character
        input = Regex.Replace(input, "(\r\n)", "|")
        Dim Lines() As String = input.Split("|")
        ' Used to access the arrPersons
        Dim idx As Integer
        ' Find the record to edit
        For idx = 0 To Lines.Length - 1
            Dim editline As String = Lines(idx)
            If Not editline = "" Then
                If editline.Substring(0, editline.IndexOf(";")).Trim = txtName.Text.Trim Then
                    ' Record was found. Replace the data with new data
                    Lines(idx) = txtName.Text.Trim & ";" & txtLast.Text.Trim & ";" & txtPhone.Text.Trim
                    FoundRec = True
                    Exit For
                End If
            End If
        Next
        ' If a modification was found write it out to INI file
        If FoundRec Then
            Dim sw As New StreamWriter("C:\Accounts.ini", False)
            input = String.Join(ControlChars.CrLf, Lines)
            sw.WriteLine(input)
            sw.Close()

            ' Get the record from the arrPersons ArrayList
            Dim p As frmMain.Persons = CType(frmMain.arrPersons(idx), frmMain.Persons)
            p.IntName = txtName.Text
            p.IntLast = txtLast.Text
            p.IntPhone = txtPhone.Text
            ' Update the ArrayList
            frmMain.arrPersons.Item(idx) = p
            ' Refresh the ListBox
            frmMain.lstAccounts.BeginUpdate()
            frmMain.lstAccounts.DataSource = Nothing
            frmMain.lstAccounts.Items.Clear()
            frmMain.lstAccounts.DisplayMember = "IntName"
            frmMain.lstAccounts.DataSource = frmMain.arrPersons
            frmMain.lstAccounts.EndUpdate()

        End If

        frmMain.Enabled = True
        frmMain.Activate()
        Me.Close()

    End Sub

End Class
Questions that need to be answered.

1. Before the user click on the cmdSave button on the edit form
    what must they do? For example fill in text boxes or select an
    item from a list box.

2. What are the names of the controls the user modifies?

3. You state that the INI file is formatted as follows:
    Name;Last;Phone
    How do you select the record to modify from the above fields?

the TextBoxes contain the information already!
he is just maybe changing from name1 to name2
or last2 to last1, cause when you click on edit you see:

Name: Bob
Last: Hiew
Phone: 12456
1. Before the user click on the cmdSave button on the edit form
    what must they do? For example fill in text boxes or select an
    item from a list box.

the TextBoxes contain the information already!
he is just maybe changing from name1 to name2
or last2 to last1, cause when you click on edit you see:

Name: Bob
Last: Hiew
Phone: 12456

So I am assuming that all three Text box's are filled in befor the save button is click? True or False?

True!
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Fernando, im still having trouble with your code. I meant edit to change from

Bob to Mike
Anderson to Piterson
123-123-123 to 456-456-456

but with your code im only allowed to change first name and last name!
is there anyway to make it work for everything ?
check here to answer http:Q_21835753.html
Hi aplelois;

You have a design problem as I had explained in one of my earlier post. The problem is you have an Accounts.ini file and you wish to modify one of the records. The three fields in the record are First Name; Last Name; Phone Number. As I see it you have two options. The first is to add another field to the Accounts.ini file this will unique identify the record within the file. This will also allow you to uniquely identify the row and to change any of the other fields in the record. The second is to place another set of text boxes on the edit form, one set will be used to locate the record in the Accounts.ini file and the other set to enter the information to update the record. I hope that this is of some help to correcting you issue.

Fernando
thanks. do you think that making something like this will be a better way??

>>Accounts.ini

[Account_01]
Text_Name=Bob
Text_Last=Anderson
Text_Phone=123-123-1234

[Account_02]
Text_Name=Dan
Text_Last=Pit
Text_Phone=654-658-6548
I just looking for the best way, it doesnt really have to be First Name; Last Name; Phone Number
The ini format you have above would be fine however it takes 5 lines to put 1 account into the ini file which uses space fast!

The method that I've found to be most productive is the format below.  However, whichever way you find easiest to code is your best bet.

The format below is pipe delimited ( | ) and has Unique_ID, First Name, Last Name, Phone.  You can change it anyway you want but a unique ID is ideal to have.

Account_01=Bob|Anderson|123-123-1234
Account_02=Dan|Pit|654-658-6548
ohh great, so what do you think FernandoSoto ? will it be easy to code?
lets move on into http:Q_21835753.html since this is closed already!
aplelois,

i'd suggest that you go with whatever you find easiest to implement.  If you implement other people's ideas and suggestions it can be a maintanence nightmare if you don't fully understand what's going on.  However, if you implement your own ideas then you (ideally) will be able to maintain your own code and start pumping out code quickly and accurately.
I think that the way you had it before, on a different post, is the way to go.

UniqueID;FirstName;LastName;Email;Phone

The code I originally gave above, Date: 05/01/2006 07:37PM PDT, gave the solution for that format.

Fernando
I have uploaded the source to a site so you can check it, here.
http://rapidshare.de/files/19529169/Accounts.zip.html
please help me!