gpt4 book ai didi

vb.net - Visual Basic 顺序访问文件

转载 作者:行者123 更新时间:2023-12-02 09:20:59 28 4
gpt4 key购买 nike

我已经为这项任务工作了一段时间了,但我几乎要抓狂了。在有人抢先说我正在寻找作业的免费讲义之前,请注意,我已经完成了 90% 的作业!该程序的列表中有 4 个广告,您可以选择投票给哪一个,它会保存您的选票并进行统计。当它在程序中进行计数时,它也会将其保存到文件中。下次打开文件时,您可以点击“显示投票”,它会读取文件并为用户重新统计所有内容。

Image of OP's Form

这是程序的样子,至少是我所做的。我的问题是,当我点击显示投票时,什么也没有发生。它不会从文件中读取任何内容。我使用消息框对其进行了测试,以查看它是否显示文件中的任何内容,并且它实际上确实显示了项目中的第一项。大家有什么想法吗?!

Public Class frmMain

Dim intVotes(3) As Integer


Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

lstCom.Items.Add("Budweiser")
lstCom.Items.Add("FedEx")
lstCom.Items.Add("E*Trade")
lstCom.Items.Add("Pepsi")
lstCom.SelectedIndex = 0

End Sub

Private Sub btnSaveVote_Click(sender As Object, e As EventArgs) Handles btnSaveVote.Click


Dim outFile As IO.StreamWriter
Dim intSub As Integer




intSub = lstCom.SelectedIndex

If intSub <= intVotes.GetUpperBound(0) Then
intVotes(intSub) += 1

If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.CreateText("CallerVotes.txt")
If lstCom.SelectedIndex = 0 Then
outFile.WriteLine("Budweiser")
ElseIf lstCom.SelectedIndex = 1 Then
outFile.WriteLine("FedEx")

ElseIf lstCom.SelectedIndex = 2 Then
outFile.WriteLine("E*TRADE")
ElseIf lstCom.SelectedIndex = 3 Then
outFile.WriteLine("Pepsi")
End If
outFile.Close()
End If
End If


lblBud.Text = intVotes(0).ToString
lblFed.Text = intVotes(1).ToString
lblET.Text = intVotes(2).ToString
lblPep.Text = intVotes(3).ToString


End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCom.SelectedIndexChanged


End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub

Private Sub btnDisplayVote_Click(sender As Object, e As EventArgs) Handles btnDisplayVote.Click



Dim inFile As IO.StreamReader
Dim strText As String

If IO.File.Exists("CallerVotes.txt") Then
inFile = IO.File.OpenText("CallerVotes.txt")
Do Until inFile.Peek = -1
strText = inFile.ReadLine
If strText = "Budweiser" Then
intVotes(0) += 1
ElseIf strText = "FedEx" Then
intVotes(1) += 1
ElseIf strText = "E*TRADE" Then
intVotes(2) += 1
ElseIf strText = "Pepsi" Then
intVotes(3) += 1
End If
Loop
inFile.Close()
End If

End Sub
End Class

最佳答案

如果您查看您的文件,我想您会发现只有一个条目。每次使用 CreateText 单击保存按钮时,您都会覆盖该文件。方法。

来自 MSDN(强调我的)

This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten.

尝试使用AppendText方法代替。

If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.AppendText("CallerVotes.txt")

您还需要根据 DeanOC 的答案将读入的值分配给适当的标签。

关于vb.net - Visual Basic 顺序访问文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29585258/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com