从Combobox中获取所选项目

Pau*_*lon 2 vb.net combobox winforms

我有一个带有来自DataTable的项目的组合框,当表单加载时执行ff:

dbConnection = New SqlCeConnection("Data Source=Journal.sdf")
dbDataAdapter = New SqlCeDataAdapter("SELECT * FROM setting_unit", dbConnection)
dbDataAdapter.Fill(dbTable)
cbxSettingsUnit.DataSource = New BindingSource(dbTable, Nothing)
cbxSettingsUnit.DisplayMember = "name"
cbxSettingsUnit.ValueMember = "name"
Run Code Online (Sandbox Code Playgroud)

当combox框中发生更改时的方法:

Private Sub cbxSettingsUnit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxSettingsUnit.SelectedIndexChanged
   tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
   MessageBox.Show(tempString)
End Sub
Run Code Online (Sandbox Code Playgroud)

该行有错误:

tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
Run Code Online (Sandbox Code Playgroud)

如何从combox框中获取所选项目?

Bjø*_*sjå 7

大多数.net "列表控件"都有一个DataSource属性搜索IListSource的实现.因此,如果您将DataTable数据源设置为数据源,则实际上将其设置DataTable.DefaultView为数据源.

Me.ComboBox1.DataSource = myDataTabele
Run Code Online (Sandbox Code Playgroud)

等于

Me.ComboBox1.DataSource = myDataTabele.DefaultView
Run Code Online (Sandbox Code Playgroud)

所以现在你有一个包含类型项的ComboBox DataRowView.

Dim selectedRowView As DataRowView = DirectCast(Me.ComboBox1.SelectedItem, DataRowView)
Dim selectedDisplayMemberValue As String = Me.ComboBox1.SelectedText
Dim selectValueMemberValue As Object = Me.ComboBox1.SelectedValue
Run Code Online (Sandbox Code Playgroud)

这就是你应该怎么做的:

Private Sub cbxSettingsUnit_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxSettingsUnit.SelectedIndexChanged
    Dim item As DataRowView = TryCast(Me.cbxSettingsUnit.SelectedItem, DataRowView)
    If (Not item Is Nothing) Then
        With item.Row
            'You have now access to the row of your table.
            Dim columnValue1 As String = .Item("MyColumnName1").ToString()
            Dim columnValue2 As String = .Item("MyColumnName2").ToString()
        End With
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

那么你为什么会收到错误?是的,您正在尝试将DataRowView转换为Integer.

'                                                                      |
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
Run Code Online (Sandbox Code Playgroud)