【问题标题】:VB.NET - cannot exit For/Next loopVB.NET - 无法退出 For/Next 循环
【发布时间】:2016-03-14 22:59:34
【问题描述】:

我正在开发一个非常简单的工作时钟应用程序。我有一个填充了员工姓名的组合框和一个显示哪些员工已登录的列表框。如果员工已经登录(显示在 ListIn 列表框中),则子应通知用户并退出而不尝试添加该人再次添加到 ListIn 框中。不幸的是,我收到“已经打卡”消息,但此人再次添加到 ListIn 框中。

这是我的代码:

Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
    For i As Integer = 0 To listIn.Items.Count - 1
        If (listIn.Items(i).ToString.Contains(cboEmployees.SelectedItem)) Then
            MsgBox("Error - employee is already clocked in.", vbOKOnly, "Error")
            Exit For
        Else
            listIn.Items.Add(cboEmployees.SelectedItem)
            timerDateTime.Stop() ' Turn off the timer, prepare to display the clock-in label.
            lblTime.Text = "Success!"
            lblDate.Text = "You are clocked in."
            timerLabel.Start() ' Turn on the timer for the clock-in label.
        End If
    Next
    cboEmployees.SelectedIndex = 0 ' After clocking in, set dropdown box to blank, disables buttons again.
    listIn.Refresh()
End Sub

对于这个小问题的任何帮助将不胜感激。我正在使用 VB.NET 2010 Professional,如果这很重要的话。

谢谢大家。

【问题讨论】:

  • 你试过调试了吗?
  • a) 打开 Option Strict b) 您正在添加到循环中的列表中,以便在有人打卡后,您还应该得到已经打卡的 msg c) 如果控件使用 DataSource 你可能很容易过滤。

标签: vb.net combobox listbox


【解决方案1】:

您在这里重叠了两个不同的任务:搜索列表和更新列表。在 For 循环中,您正在测试当前条目是否与员工匹配,如果不匹配,则添加员工。这意味着除非第一个条目与员工匹配,否则您将执行 If 语句的“Else”部分,并添加员工。因此,即使第二个条目匹配,也为时已晚——您已经添加了员工,因为第一个条目不匹配。

您想要做的是将搜索与更新分开。创建一个名为“isClockedIn”之类的布尔变量并将其设置为 false。然后通过您的 For 循环,如果条目匹配,则将 isClockedIn 设置为 true 并退出循环。然后,在 For 循环之后,执行另一个 If 语句来检查 isClockedIn 并更新列表或显示错误。

【讨论】:

  • 谢谢你,MarkNFI - 效果很好。非常感激。我在学习……慢慢地,但是在学习。最好的祝愿,
【解决方案2】:

完整的工作代码,以防其他人遇到此问题。

Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.Click
    Dim isIn As Boolean = False
    For i As Integer = 0 To listIn.Items.Count - 1
        If (listIn.Items(i).ToString.Contains(cboEmployees.SelectedItem)) Then
            isIn = True
            MsgBox("Error - employee is already clocked in.", vbOKOnly, "Error")
            Exit For
        End If
    Next
    If isIn = False Then
        listIn.Items.Add(cboEmployees.SelectedItem)
        timerDateTime.Stop() ' Turn off the timer, prepare to display the clock-in label.
        lblTime.Text = "Success!"
        lblDate.Text = "You are clocked in."
        timerLabel.Start() ' Turn on the timer for the clock-in label.
    End If


    cboEmployees.SelectedIndex = 0 ' After clocking in, set dropdown box to blank, disables buttons again.
    listIn.Refresh()
End Sub

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 2023-03-22
    • 2020-11-23
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多