在我的代码中,我有4个按钮。我的“搜索按钮”(按钮2)和我的“查看数据按钮”(按钮4)出现问题。我一直在收到我似乎无法解决的错误。我只是想知道是否有人能够帮助我。先感谢您。 详细信息写在代码之间,这样你就可以看到我遇到问题的地方。
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim pInventory As IO.StreamWriter = IO.File.AppendText("product.txt")
If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Then
MsgBox("Please fill in required fields", MsgBoxStyle.Exclamation, "Error")
Else
pInventory.WriteLine(TextBox1.Text & ", $" & TextBox2.Text & ", " & TextBox3.Text)
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
Dim num As Integer
For num = 0 To ListBox1.Items.Count - 1
pInventory.WriteLine(ListBox1.Items(num))
Next
pInventory.Close()
End If
End Sub
'此处我无法搜索在数据条目中输入/保存的产品 '它告诉我异常未得到处理。它说它是一个无效的论点
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim name As String
Dim num As Integer
Dim max As Integer
name = InputBox("What item would you like to search for :", "Product Search")
num = 0
max = ListBox1.Items.Count - 1
问题在这里(num)
Do While (name <> (ListBox1.Items.Item(num))) And (num < max)
num = num + 1
ListBox1.Items.Add(num)
Loop
If (name = ListBox1.Items.Item(num)) Then
MsgBox(name & " Was found", , "Search")
Else
MsgBox(name & " Was not found", , "Search")
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If ListBox1.SelectedIndex <> -1 Then
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
Else
MsgBox("Please make a selection")
End If
End Sub
'在这里,当你点击button4(“查看数据”)按钮时,我只想让存档显示在数据输入中输入的所有内容 '但我似乎无法将其显示在只显示数据的位置,而不是要求您输入存档名称 “我想我刚刚用这个项目搞定了!”
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim item As String
Dim product As StreamReader
item = InputBox("Please enter archive name", "Product List")
item = item & ".txt"
If File.Exists(item) Then
product = File.OpenText(item)
ListBox1.Items.Clear()
Do While product.Peek <> -1
ListBox1.Items.Add(product.ReadLine)
Loop
product.Close()
Else
MsgBox("Archive does not exist!", MsgBoxStyle.Critical, "Error")
End If
End Sub
End Class
答案 0 :(得分:0)
Do While (name <> (ListBox1.Items.Item(num))) And (num < max)
在上面的代码中,如果您的ListBox不包含任何项目ListBox1.Items.Item(num)
将触发异常, ArgumentOutOfRangeException 。您可以添加条件以确保ListBox1包含一些项目:
Do While (ListBox1.Items.Count > 0 AndAlso name <> (ListBox1.Items.Item(num))) And (num < max)
单击Button4,您要显示文件中的所有数据而不询问文件名?如果是这种情况,您可以在模块级别声明的全局常量中对文件名进行硬编码,然后您可以在需要时从该常量中获取文件名,例如:
Public Const ArchieveName As String = "Product.txt"
...
item = ArchieveName
您也在Button1点击事件上对文件名进行了硬编码。