每0.8秒来自列表框的随机项

时间:2018-08-18 19:02:28

标签: vb.net random listbox

我有一个在下面看到的代码。你能告诉我如何优化吗?因为有时当我单击随机选择器时(此代码每0.8秒显示一次随机项目,例如“滚轮”),所以没有显示f就像我定义的20项...我只是想通过以下方式使此脚本起作用:我单击一个按钮,它正在滚动列表框中的位置,并显示不是的项目

Dim rnd As New Random
Dim rndIndex As Integer = rnd.Next(10, 20)

For ill As Integer = 0 To rndIndex
    Dim rnd As New Random
    Dim randomIndex As Integer = rnd.Next(0, lCount)
    If Not Label1.Text = ListBox1.Items(randomIndex) Then
        Label1.Text = ListBox1.Items(randomIndex)
        Delay(0.08)
    Else
        rndIndex = rndIndex + 1
    End If
Next

那是行不通的,因为有时我只能看到6-8个不同的项目。可能是这样的:我有10个数字(0-9),并且每0.8秒将以下数字放入标签中: 1、5、7、4、3、1、5、8 ,6、3、0、3、1、5

1 个答案:

答案 0 :(得分:2)

我不是100%肯定我应该这样做,但是您的代码有很多错误,要逐步解决它会很困难。基本上,这是我如何每0.8秒从ListBox中的Label中显示一个随机项目,而不必连续两次重复同一项目:

Private ReadOnly rng As New Random

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'This is done in code here for clarity but you'd normally do this in the designer.
    Timer1.Interval = 800
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    'Get all the items from the ListBox.
    Dim items = ListBox1.Items.Cast(Of String)().ToList()

    'Remove the currently displayed item.
    items.Remove(Label1.Text)

    'Get a random item from the remainder and display it.
    Label1.Text = items(rng.Next(items.Count))
End Sub

正如我在评论中所说,没有循环。 Timer组件专门用于要定期执行操作的情况。还要注意,即使在生成随机数之前,当前显示的项目也已从等式中删除,因此重复不会有问题。

编辑:

这里是根据我第一次想念的内容修改的代码:

Private ReadOnly rng As New Random
Private tickCount As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'This is done in code here for clarity but you'd normally do this in the designer.
    Timer1.Interval = 800
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    tickCount = rng.Next(10, 20)
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    tickCount -= 1

    If tickCount = 0 Then
        Timer1.Stop()
    End If

    'Get all the items from the ListBox.
    Dim items = ListBox1.Items.Cast(Of String)().ToList()

    'Remove the currently displayed item.
    items.Remove(Label1.Text)

    'Get a random item from the remainder and display it.
    Label1.Text = items(rng.Next(items.Count))
End Sub

我还对原始代码做了一些修改,因为最后一行是从ListBox1.Items而不是items处以随机索引获取项目。