我的VB表单中有1个文本框和1个列表框。
我想检查重复的项目,与textbox.text1和listbox.list项目进行比较。
如果textbox.text1值为'3333'且listbox.list多值为'1111''2222''3333''4444'
那么如何实现像重复检查例程一样?
因此,如果重复检测与当前text1值进行比较,则与列表框中的一个进行比较
值是if detect,想要弹出消息框
提前致谢
答案 0 :(得分:2)
假设您要在ListBox中插入字符串,您可以这样做:
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim x As String
For Each x In ListBox1.Items
If (x = TextBox1.Text) Then
MessageBox.Show("Error")
Return
End If
Next
ListBox1.Items.Add(TextBox1.Text)
End Sub
如果它是具有名为Value的属性的另一种类型的对象,那么您需要进行一些小改动:
Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim x As Foo
For Each x In ListBox1.Items
If (x.Value = TextBox1.Text) Then
MessageBox.Show("Error")
Return
End If
Next
ListBox1.Items.Add(TextBox1.Text)
End Sub
答案 1 :(得分:1)
假设ListBox
包含字符串,您可以使用Contains
集合的Items
方法检查匹配项。示例(制作一个名为'_TheListBox'的ListBox
表单,一个名为'_TextBox'的TextBox
和一个名为'_theLabel'的Label
表单:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_theListBox.Items.AddRange(New String() {"aaaa", "bbbb", "cccc", "dddd"})
End Sub
Private Sub _theTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _theTextBox.TextChanged
If ListBoxContainsItem(_theListBox, _theTextBox.Text) Then
_theLabel.Text = "It's a match"
Else
_theLabel.Text = ""
End If
End Sub
Private Function ListBoxContainsItem(ByVal lb As ListBox, ByVal text As String) As Boolean
' check if the string is present in the list '
Return lb.Items.Contains(text)
End Function