2014-01-19 76 views
0

我有一个组合框和一个列表框。 我想要的是,当我从组合框中选择一个值(文本)来检查列表框中是否有相同的值(相同的文本),如果有,则msgbox应显示为“数据找到”如何比较组合框值与列表框中的项目 - vb.net

我想这段代码,但它不是事先工作

暗淡我作为整数

For i = 0 To ListBox1.Items.Count - 1 
     If ComboBox1.SelectedItem = ListBox1.ValueMember Then 
      MsgBox("DATA FOUND") 
     End If 

    Next i 

感谢....

回答

2

您使用的是有你比较不同的含义两个属性。 SelectedItem是一个对象(可能取决于你如何填补组合是任何东西,ValueMember是在ListBox中的项目的实际值使用属性的只是名字。

但是两个类(ListBox和组合框)共享存储的列表项,那么假设都被填充使用字符串列表相同的模式,然后你的代码可能是

Dim curComboItem = ComboBox1.SelectedItem.ToString() 
For i = 0 To ListBox1.Items.Count - 1 
    If curComboItem = ListBox1.Items(i).ToString() Then 
     MsgBox("DATA FOUND") 
     Exit For 
    End If 
Next i 
0
If ComboBox1.SelectedItem = ListBox1.ValueMember Then 

应该

If ComboBox1.SelectedItem = ListBox1.Items(i) Then 

请注意, ComboBox1.SelectedItem 只适用于集合内的项目。您可以通过 .text 参数将其扩展为任何文本。

P.D.

Next i '??? 
0

使用您的ComboBoxListBox实物往往会导致你的应用程序更好的灵活性。

例如,您有一个汽车大量的应用程序,其中有很长的可用汽车列表,并且您不想浏览整个列表 - 您使用ComboBox选择制造商和型号,并且使用这些商品在你的列表框中。

(in pseudo-code)

您的车对象。

class Car 
    ModelId 
    ModelMake 
    ModelName 
    FullName = ModelMake & " " & ModelName 
End Class 

class AvailableCar Inherits Car 
    IsOnTheLot 
    VIN 
    Price 
    'etc 
End Class 

在您的Form类

comboCarMakes.DataSource = GetListOfMakesOfCars() ' List of Car classes 
comboCarMakes.ValueMember = "ModelId" 
comboCarMakes.DisplayMember = "FullName" 

listAvbailableCars.DataSource = GetListOfAvailableCars() ' List of AvailableCar classes 
listAvbailableCars.ValueMember = "VIN" 
listAvbailableCars.DisplayMember = "FullName" 

Sub comboCarMakes_SelectedIndexChanged 


    Dim car as Car = DirectCast(comboCarMakes.SelectedItem, Car) 
    For i = 0 To listAvbailableCars.Items.Count - 1 
     If car.ModelId = DirectCast(listAvbailableCars.Items(i), AvailableCar).ModelId Then 
      ' Do something 
     End If 
    Next 
End Sub 

优势 - 你有很多的立即可用的信息。

相关问题