我有一个包含来自 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"
组合框发生变化时的方法:
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
如何从组合框中获取所选项目?
最佳答案
大多数.net “listing-controls” 拥有DataSource
属性搜索IListSource 的实现.因此,如果您将 DataTable
设置为数据源,您实际上是将 DataTable.DefaultView
设置为数据源。
Me.ComboBox1.DataSource = myDataTabele
等于
Me.ComboBox1.DataSource = myDataTabele.DefaultView
所以现在你有一个包含 DataRowView
类型项目的 ComboBox。
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
关于vb.net - 从组合框中获取所选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20780229/