从Combobox中获取所选项目

时间:2013-12-26 06:31:44

标签: vb.net winforms combobox

我有一个带有来自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"

当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

该行有错误:

tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString

如何从收件箱中获取所选项目?

5 个答案:

答案 0 :(得分:7)

大多数.net “listing-controls”谁拥有DataSource属性搜索IListSource的实现。因此,如果您将DataTable设置为数据源,则实际上是将DataTable.DefaultView设置为数据源。

Me.ComboBox1.DataSource = myDataTabele

等于

Me.ComboBox1.DataSource = myDataTabele.DefaultView

现在你有一个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

这就是你应该这样做的方式:

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

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

'                                                                      |
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString

答案 1 :(得分:1)

试试这个:

Dim row_v As DataRowView = comboBox1.SelectedItem
        Dim row As DataRow = row_v.Row
        Dim itemName As String = row(0).ToString()

答案 2 :(得分:0)

你必须使用这个

tempString = cbxSettingsUnit.Items(cbxSettingsUnit.SelectedIndex).ToString

答案 3 :(得分:0)

尝试使用以下代码

Try
        DS = New DataSet
        Tabel = "SELECT * FROM setting_unit"
        Dim CB As New OleDb.OleDbDataAdapter(Tabel, dbConnection)
        CB.Fill(DS, "setting_unit")
    '
        Me.cbxSettingsUnit.DataSource = Prf.Tables(0)

        Me.cbxSettingsUnit.ValueMember = "name"
        Me.cbxSettingsUnit.DisplayMember = "name"
    Catch ex As Exception
    End Try

答案 4 :(得分:-1)

试试这个:

combo.datasource = datatable
combo.displaymember = "abbreviation"
combo.valuemember = "abbreviation"

然后获取所选项目:

SelectionChangeCommitted 组合框的事件中输入:

    tmpString=combo.selectedvalue
    msgBox(tmpString)