VB.NET ComboBox 结果选中项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17131671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:56:59  来源:igfitidea点击:

VB.NET ComboBox results selected item

vb.netcomboboxselection

提问by Zen

Hi I have a vb windows form application that has a ComboBox from the form1 I have some code that reads some registry and adds item results to combobox. I would like to select one of the results and run a start process. My problem is where do I put the code when item is selected then do something and how to I determine what has been selected?

嗨,我有一个 vb windows 窗体应用程序,它有一个来自 form1 的 ComboBox 我有一些代码可以读取一些注册表并将项目结果添加到组合框。我想选择一个结果并运行一个启动过程。我的问题是选择项目时我应该把代码放在哪里然后做一些事情以及如何确定已选择的内容?

My Code to query registry keys

我的代码来查询注册表项

 Dim Key, Reader As RegistryKey, Y As String
    Key = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts", False)
    For Each X In Key.GetSubKeyNames
        Reader = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts\" & X, False)
        If Reader.GetValueNames().Contains("AppTitle") Then
            Y = Reader.GetValue("AppTitle")

            If Not ComboBox1.Items.Contains(Y) Then ComboBox1.Items.Add(Y)
        End If

If i do somehting like this, it just shows a blank messagebox and I have not selected that text from combobox yet.

如果我这样做,它只会显示一个空白的消息框,而我还没有从组合框中选择该文本。

If ComboBox1.SelectedText Then
            MessageBox.Show(ComboBox1.SelectedText())
        End If

采纳答案by Steve

You subscribe to the SelectedIndexChangedevent writing a method like this

您订阅SelectedIndexChanged事件,编写这样的方法

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

    Dim comboBox As comboBox = CType(sender, comboBox)

    ' Caution, the event could be called also when there is nothing selected
    if combBox.SelectedItem IsNot Nothing Then
         Dim curValue = CType(combBox.SelectedItem, String)
         'do your stuff with the selected key' 
    End If
End Sub 

回答by Milan Sheth

if combBox.SelectedItem IsNot Nothing Then

    Dim cmbselected As String = DirectCast(DirectCast(DirectCast(DirectCast(combBox, System.Windows.Controls.ComboBox).SelectedValue, System.Object), System.Data.DataRowView).Row, System.Data.DataRow).ItemArray(0)

End If