【问题标题】:Set Combobox Value base on another Combobox Selected Value - VB.NET根据另一个组合框选定值设置组合框值 - VB.NET
【发布时间】:2014-08-07 14:17:04
【问题描述】:

我有两个组合框。如果用户从第一个组合框中选择某个值,那么我希望第二个组合框自动更改并选择其相应的值。

例如:

If Me.InstitutionAdvisoryFirmsComboBox1.SelectedValue = 3 Then 
     Me.WeightComboBox1.SelectedValue = 2

我也试过了:

If Me.InstitutionAdvisoryFirmsComboBox1.SelectedText = "Internal Guidelines" Then                 
    Me.WeightComboBox1.SelectedText = "None"

谁能帮忙?

【问题讨论】:

  • 你有没有通过代码来查看 SelectedValue 等于什么?我的猜测是您没有将 ValueMemeber 设置为您认为您所做的事情。
  • 盒子里有什么?如果它们只是字符串,请尝试 SelectedItem。 SelectedText 用于显示字符串中实际突出显示的文本。
  • 组合框是否在这些代码行之前添加了任何项目?如果您执行“selected text = something”,则应在该代码行之前将某些内容添加到项目中。
  • @LarsTech 我尝试了 SelectedItem 并收到一条错误消息,指出“键入 Double 的转换字符串“内部指南”无效”
  • @sparkysword 是的,组合框在代码之前添加了项目。我做了什么来填充组合框,我必须首先编写一个 SQL 查询,因为它从我的数据库中提取并使用 For i ....items.add(sqltable.Rows(i)(...)

标签: vb.net combobox


【解决方案1】:
//selected index changed event for the combo box 

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles InstitutionAdvisoryFirmsComboBox1.SelectedIndexChanged

    If Me.InstitutionAdvisoryFirmsComboBox1.SelectedIndex = 3 Then 
        If Me.WeightComboBox1.Items.Count >= 2 Then // make sure you are not accessing an index out of range
            Me.WeightComboBox1.SelectedIndex = 2
        End If
    End If

End Sub 

【讨论】:

  • 我收到一条错误消息,指出“InvalidArgument = Value of 2 is not valide for SelectedIndex.
  • 组合框中有 3 个项目吗?
  • 是的,我的第二个组合框中有 3 个项目。正好 3 项
  • 当您使用额外的 if 语句运行此代码时会发生什么?
【解决方案2】:

您需要为您正在检查的comboBox 使用事件处理程序。在事件处理程序中,您可以使用 if 语句的细微变化:

If Me.InstitutionAdvisoryFirmsComboBox1.SelectedIndex = 1 Then                 
    Me.WeightComboBox1.SelectedIndex = 2

使用SelectedIndex函数时,从第0个位置开始计数。

当使用SelectedValueSelectedItem 来获取combobox 中的文本或值时。

Dim ComboValue As String = comboBox1.SelectedValue.ToString();

Dim ComboValue As String = comboBox1.SelectedItem.ToString();

【讨论】:

  • 我已经尝试过,正如另一个用户之前建议的那样,但是我收到一条错误消息,指出“InvalidArgument = Value of 2 is not valid for SelectedIndex.”
  • 我有 3 件商品。我想选择第三项,因此我把 SelectedIndex = 2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多