从Combobox中获取所选项目

 涛之圣首到 发布于 2023-02-08 10:13

我有一个带有来自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框中获取所选项目?

1 个回答
  • 大多数.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
    

    2023-02-08 10:15 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有