Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click Dim comboBoxValue As String = ComboBox1.Text Dim filePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "abc.txt") If File.Exists(filePath) Then Dim existingText As String = File.ReadAllText(filePath) Dim lines() As String = existingText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries) Dim updatedLines As New List(Of String)() ' 遍历每一行 For Each line As String In lines ' 检查行是否以ComboBox1的值开头 If Not line.StartsWith(comboBoxValue & ",") Then ' 不是匹配的行,将其添加到更新列表中 updatedLines.Add(line) End If Next File.WriteAllText(filePath, String.Join(Environment.NewLine, updatedLines)) MessageBox.Show("已成功删除文本文件中对应的行。") Else MessageBox.Show("文本文件不存在。") End If End Sub 修改以上代码的BUG
时间: 2024-02-10 18:16:25 浏览: 148
常用控件的使用(Button、TextBox、ComboBox、ListBox等)
5星 · 资源好评率100%
这段代码可能存在的问题是,如果文本文件中没有以ComboBox1的值开头的行,那么updatedLines列表将为空,而File.WriteAllText方法将写入一个空字符串到文件中,导致删除失败。可以通过添加一个条件语句来避免这个问题:
```
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
Dim comboBoxValue As String = ComboBox1.Text
Dim filePath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "abc.txt")
If File.Exists(filePath) Then
Dim existingText As String = File.ReadAllText(filePath)
Dim lines() As String = existingText.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
Dim updatedLines As New List(Of String)()
For Each line As String In lines
If Not line.StartsWith(comboBoxValue & ",") Then
updatedLines.Add(line)
End If
Next
If updatedLines.Count > 0 Then ' 如果有匹配的行
File.WriteAllText(filePath, String.Join(Environment.NewLine, updatedLines))
MessageBox.Show("已成功删除文本文件中对应的行。")
Else ' 如果没有匹配的行
MessageBox.Show("没有找到要删除的行。")
End If
Else
MessageBox.Show("文本文件不存在。")
End If
End Sub
```
阅读全文