Marc Intes
Marc Intes

Reputation: 737

Delete/edit/add a line of text from a text file

My starting code would read all the lines from a textfile and placing them in an array

Public textArray As String()
textArray = File.ReadAllLines("textfile.txt")

I want to be able to delete a line of text, edit a line of text and add a line text to the textfile. My idea would be displaying all the lines of text in rows where I could click one line and the text will be placed in a textbox, from that textbox I can edit the text. Delete, edit and add would be three separate buttons.

I need a starting code, I am confused on how to start this.

Upvotes: 0

Views: 5995

Answers (2)

tinstaafl
tinstaafl

Reputation: 6948

A listbox would be well suited to your task. Loading the file is as simple as using the AddRange method of the items collection, ListBox1.Items.AddRange(File.ReadAllLines("textfile.txt")).

Saving the data is just as simple with File.WriteAllLines, File.WriteAllLines("textfile.txt", ListBox1.Items).

To edit the data you can use buttons and read the selected line in the listbox or you can handle the selected indexchanged event

Upvotes: 1

cdMinix
cdMinix

Reputation: 675

I would recommend a Streamreader and ReadLine() for reading all lines and a List for saving them.

So the code for the reading + saving would be:

Dim lineList As New List(Of String)()

Dim sr As StreamReader = New StreamReader(path)

    Do While sr.Peek() >= 0
         lineList.add(sr.ReadLine())
    Loop

Then add some labels (with the text) to your form:

For i as Integer = 0 to lineList.Count - 1
    Dim Label as New Label
    lineLabel.Text = lineList.Item(i)
    lineLabel.Location = New Point(0, 50 * i) 'you can change the 50 to whatever value you want
    Me.Controls.Add(Label)
    AddHandler Label.Click, AddressOf Me.Label_Click 'here we add a handler for the label-clicks
Next

The handler will look like this then:

 Private Sub Label_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'handle the label clicks here
 End Sub

Upvotes: 0

Related Questions