我有一个带有来自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
如何从combox框中获取所选项目?
大多数.net "列表控件"都有一个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转换为Integer.
' | tempString = cbxSettingsBusinessUnit.Items(cbxSettingsBusinessUnit.SelectedItem).ToString