vb.net 从文本文件中删除/编辑/添加一行文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18011170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delete/edit/add a line of text from a text file
提问by Marc Intes
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.
我需要一个起始代码,我对如何开始这个感到困惑。
回答by tinstaafl
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")).
列表框非常适合您的任务。加载文件就像使用 items 集合的 AddRange 方法一样简单ListBox1.Items.AddRange(File.ReadAllLines("textfile.txt"))。
Saving the data is just as simple with File.WriteAllLines, File.WriteAllLines("textfile.txt", ListBox1.Items).
使用 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
要编辑数据,您可以使用按钮并读取列表框中的选定行,或者您可以处理选定的 indexchanged 事件
回答by cdMinix
I would recommend a Streamreaderand ReadLine()for reading all lines and a Listfor saving them.
我建议使用StreamreaderandReadLine()阅读所有行,使用 aList保存它们。
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

