我有一个组合框,其中包含数据表中的项目,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"
组合框有变化时的方法:
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
如何从组合框中获取所选项目?
大多数拥有 DataSource
属性的 .net
“listing-controls”都会搜索 IListSource 的实现。因此,如果您将
DataTable
设置为数据源,则实际上是将 DataTable.DefaultView
设置为数据源。
Me.ComboBox1.DataSource = myDataTabele
等于
Me.ComboBox1.DataSource = myDataTabele.DefaultView
现在你有了一个包含
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 转换为 Integer。
' |
tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString
试试这个:
Dim row_v As DataRowView = comboBox1.SelectedItem
Dim row As DataRow = row_v.Row
Dim itemName As String = row(0).ToString()
你必须使用这个
tempString = cbxSettingsUnit.Items(cbxSettingsUnit.SelectedIndex).ToString
尝试使用下面的代码
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
tempString = cbxSettingsUnit(cbxSettingsUnit.SelectedIndex).Itemdata
试试这个:
combo.datasource = datatable
combo.displaymember = "abbreviation"
combo.valuemember = "abbreviation"
然后使用以下命令获取所选项目:
在组合框的 SelectionChangeCommissed 事件上放置以下内容:
tmpString=combo.selectedvalue
msgBox(tmpString)