2014-12-02 69 views
-2

我通过连接来自sql语句的数据源来填充组合框。以编程方式更改SelectedValue组合框

dt = select Name as [Name], Code as [Id] from Table 

然后我想瑟对此我用下面的代码

For Each i as DataRowView in comboBox.Items 

    If i("Name").ToString="Nick" Then 
    comboBox.SelectedIndex=selectedCount 
    Exit For 
    End If 

selectedCount=selectedCount +1 
Next 

这种定位将正确显示“尼克”在下拉框中默认的组合框“尼克”的默认值,但是当我用下面的代码去获取selectedValue时,它得到列表中第一个项目的选定索引而不是默认项目“Nick”。

当我单击按钮并查看组合框的SelectedIndex时,它将设置回0,尽管它在comboxbox中显示正确的selectedValue。

item=comboBox.SelectedValue.ToString 

如何获得所选值我默认组合框为?

+0

可能重复(http://stackoverflow.com/questions/18730262/combobox-selectedvalue-not-working:然后使用INT作为comboBoxe的项目索引设置的项目)。注意完全相同,但我一定会使用'SelectedItem'来代替。 – 2014-12-02 16:37:22

+0

你不能使用'comboBox.SelectedItem = i'吗?顺便说一句,不要忘记关闭“尼克”后面的引号。 – Andrew 2014-12-02 16:38:30

回答

0

这为我工作:

item = comboBox.Items(comboBox.SelectedIndex).ToString 

如果您的SelectedIndex莫名其妙地被恢复到0,然后声明一个int,并在循环,设置整数价值的selectedCount。 [ComboBox.SelectedValue不工作]的

Dim index as Int = 0 

For Each i as DataRowView in comboBox.Items 

    If i("Name").ToString="Nick" Then 
    comboBox.SelectedIndex=selectedCount 
    index = selectedCount 
    Exit For 
    End If 

    selectedCount=selectedCount +1 
Next 

item = comboBox.Items(index).ToString