VB.NET-无法退出For/Next循环
我正在为工作开发一个非常简单的时钟应用程序。我有一个用员工姓名填充的组合框和一个显示哪些员工登录的列表框。如果员工已登录(显示在ListIn列表框中),则sub应通知用户并退出,而无需再次尝试将该人员添加到ListIn列表框中。不幸的是,我收到了“已打卡”消息,但该人再次添加到列表框中 这是我的密码:VB.NET-无法退出For/Next循环,vb.net,combobox,listbox,Vb.net,Combobox,Listbox,我正在为工作开发一个非常简单的时钟应用程序。我有一个用员工姓名填充的组合框和一个显示哪些员工登录的列表框。如果员工已登录(显示在ListIn列表框中),则sub应通知用户并退出,而无需再次尝试将该人员添加到ListIn列表框中。不幸的是,我收到了“已打卡”消息,但该人再次添加到列表框中 这是我的密码: Private Sub btnIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnIn.
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,如果这很重要的话
谢谢大家。您在这里重复了两个不同的任务:搜索列表和更新列表。在For循环中,您正在测试当前条目是否与employee匹配,如果不匹配,则添加employee。这意味着,除非第一个条目与employee匹配,否则您将执行If语句的“Else”部分,并添加employee。因此,即使第二个条目匹配,也为时已晚——您已经添加了员工,因为第一个条目不匹配
您要做的是将搜索与更新分开。创建一个名为“isClockedIn”的布尔变量,并将其设置为false。然后遍历For循环,如果条目匹配,则将isClockedIn设置为true并退出循环。然后,在For循环之后,执行另一个If语句,检查isClockedIn并更新列表或显示错误 已完成的工作代码,以防其他人有此问题
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
你试过调试它吗?a)打开选项Strict b)你将添加到循环中的列表中,这样在给某人打卡后,你也应该得到已经打卡的消息c)如果控件使用了数据源,你可能可以很容易地对其进行过滤。谢谢你,MarkNFI-这非常有效。非常感谢。我在学习。。。慢慢地,但是学习。最美好的祝福,