使用后退/下一步按钮功能显示标签中的列表(字符串)内容

时间:2013-11-17 09:33:12

标签: .net vb.net

初始状况&目标 的 我有一个列表(字符串)由一个.txt文件中的逐行填充。我创建了一个带有标签的两个按钮(后退和下一个)。我想在标签中显示列表的当前内容,并能够使用按钮来回切换。

我的代码:

Imports System.IO

Public Class Form1
Public wb As New List(Of String)
Public i As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    btnClose.Visible = False
    btnLast.Visible = False
    lblWort.Text = "Please press Next"
    wb = Wörterbuch.Woerter("C:\Users\Words.txt")
End Sub

Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click, btnNext.Click
    'If Next was Clicked
    If sender Is btnNext Then
        btnLast.Visible = True
        'List is not at the end yes
        If i <= wb.Count - 1 Then 'count goes from 1 to 5, i goes from 0 to 4
            lblWort.Text = wb(i)
            i += 1
            'List of Words is at the end
        Else
            lblWort.Text = "Thanks, you finished the test!"
            btnLast.Visible = False
            btnNext.Visible = False
            btnClose.Visible = True
        End If
        'If back was clicked
    ElseIf sender Is btnLast Then
        If i = 0 Then
            btnLast.Visible = False
        Else
            i -= 1
            lblWort.Text = wb(i)
        End If
    End If
End Sub

Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
    Me.Close()
End Sub
End Class

我的问题: 代码运行没有错误,但是当我第一次点击“返回”(btnLast)时没有任何反应。原因是由于i+=1,计数器已经处于高位。

Alternatitly我可以将i+=1设置为:

 If sender Is btnNext Then
        i += 1

但是我遇到的问题是列表中的第二个位置首先显示的不是第一个位置。我觉得应该有一个共同的解决方案,因为这必须应用数百万次,但我找不到它。有谁可以帮我找到解决这个问题的方法?

2 个答案:

答案 0 :(得分:2)

在分析给定位置后,您不能放置i += 1,因为可能会引发算法忽略给定的索引(可能会在下次单击按钮时处理)。克服“起始问题”的方法是将i设置为-1。那就是:

If i < wb.Count - 1 Then 'count goes from 1 to 5, i goes from 0 to 4
    i += 1
    lblWort.Text = wb(i)
    'List of Words is at the end
Else
'etc

Public i As Integer = -1

答案 1 :(得分:-1)

为什么不通过初始化

将List.count和i置于相同的基础上
Public i as integer=1

然后根据需要调整其余部分

If i <= wb.Count - 1 Then

已更改为

If i <= wb.Count Then