VB.NET ComboBox 验证值是否存在

VB.NET ComboBox Verify if Value Exists

我目前正在开发 VB 中编码的应用程序。我正在对其进行修改并添加功能。

我遇到的问题是,在我尝试 select 之前,我想 运行 根据该值是否存在对 ComboBox 进行验证检查。

组合框由 sql 具有字典数据源的查询填充

Dim TimerComboSource As New Dictionary(Of String, String)()
TimerComboSource.Add(varSQLReader("ID").ToString, varSQLReader("Name").ToString)
'Binds the values to the comboboxes
cmbTimer.DataSource = New BindingSource(TimerComboSource, Nothing)
cmbTimer.DisplayMember = "Value"
cmbTimer.ValueMember = "Key"

I select 来自不同 ComboBox 的值,该值填充了不同的 SQL Query/SQL Table.

当我 select 第二个 ComboBox 值时,它来自的 table 包含第一个 ComboBox 的 ID。我想在 select 之前验证第一个 ComboBox 中是否存在该值。

以下无效:

If cmbTechnician.Items.Contains(varSQLReader("Tech_ID").ToString) Then
    cmbTechnician.SelectedValue = varSQLReader("Tech_ID").ToString
End If

在 VB 中是否有特定的方法来完成这项工作而又不会过于复杂?另一种解决方法是进行更复杂的 SQL 查询,但如果有更简单的方法,我宁愿不这样做。

由于您在字典上使用 BindingSource,因此您应该使用 DataSource 来确定事物是否存在。如果您尝试直接添加到 cmbTimer.Items 或从中删除,您会收到一条错误消息,提示您使用 DataSource。所以做同样的事情来检查是否存在(不要使用本地范围的字典):

' form or class level collection
Private cboSource As New Dictionary(Of String, String)

cboSource.Add("red", "red")
cboSource.Add("blue", "blue")
cboSource.Add("green", "green")

cbo.DataSource = New BindingSource(cboSource, Nothing)
cbo.DisplayMember = "Value"
cbo.ValueMember = "Key"

If cbo.Items.Contains("red") Then
    Console.Beep()     ' wont hit
End If

If cboSource.ContainsValue("red") Then
    Console.Beep()     ' hits!
End If

评论中的建议建议将 BindingSourceDataSource 转换回字典:

Dim tempBS As BindingSource = CType(cbo.DataSource, BindingSource)
Dim newCol As Dictionary(Of String, String) = CType(tempBS.DataSource, Dictionary(Of String, String))

If newCol.ContainsValue("red") Then
    Console.Beep()     ' hits!
End If

保留对词典的引用更容易、更直接,但重新创建它会起作用。

这是另一种方式 =>

 If cmbTechnician.FindString(varSQLReader("Tech_ID").ToString) <= -1 Then
         'Do Not Exist 
 End If

这将找到显示成员,如果存在值,将 return 行的索引,否则将 return -1.

更多信息在这里=>ComboBox.FindString