vb.net 从组合框中获取价值成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37237167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:52:55  来源:igfitidea点击:

Get value member from combo box

vb.netdatagridviewcombobox

提问by TJB

Done a fair bit of searching on this, but cannot find anything specific enough.

对此进行了大量搜索,但找不到任何足够具体的内容。

I am try to get the value member from my combobox, the reason being that the selected valuememberwill form the basis of a query to populate a datagridview.

我试图从我的组合框中获取 value 成员,原因是所选成员valuemember将构成填充 datagridview 的查询的基础。

The below code looks at dbo.Calendar on a T-SQL database. The column monthis just the number for the month i.e. 1-12 and MonthNameis as the name suggests.

下面的代码查看 T-SQL 数据库上的 dbo.Calendar。该列month只是月份的数字,即 1-12,MonthName顾名思义。

Testing the valuememberoutput in the MsgBoxcommand below, the output just gives me "month", rather than say "5" if the user selects "May" in the combobox. Consequently, I am passing the string "Month" to try to populate my datagridview when I should be passing "5". Anyone able to help on why I am not getting "5"?

valuememberMsgBox下面的命令中测试输出,如果用户在组合框中选择“May”,输出只会给我“月”,而不是“5”。因此,当我应该传递“5”时,我传递了字符串“Month”来尝试填充我的 datagridview。任何人都可以帮助解释为什么我没有得到“5”?

Dim command As SqlCommand
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim sql As String
        sql = "select distinct month, MonthName from Calendar order by month asc"
        Try
            conn.Open()
            command = New SqlCommand(sql, conn)
            adapter.SelectCommand = command
            adapter.Fill(ds)
            adapter.Dispose()
            Command.Dispose()
            conn.Close()
            MonthSearch.DataSource = ds.Tables(0)
            MonthSearch.ValueMember = "month"
            MonthSearch.DisplayMember = "MonthName"
            MsgBox(MonthSearch.ValueMember)
        Catch ex As Exception
            MessageBox.Show("Cannot open connection! ")
        End Try

回答by Andrew Morton

The ValueMemberrefers to the name of the column in the datatable which it is to use for the values.

ValueMember是指在数据表列,它是使用了值的名称。

The property you want to refer to is SelectedValue:

您要引用的属性是SelectedValue

Option Infer On

Imports System.Data.SqlClient

Public Class Form1

    Sub SetUpMonthsCB()
        Dim dt As New DataTable

        Dim scsb As New SqlConnectionStringBuilder
        scsb.DataSource = ".\SQLEXPRESS"
        scsb.InitialCatalog = "testing"
        scsb.IntegratedSecurity = True

        Try
            Using sqlConn As New SqlConnection(scsb.ConnectionString)
                ' Here I used an existing table in my database, hence the different SQL.
                Dim sql = "SELECT DISTINCT M AS month, DATENAME(month, dt) AS MonthName FROM Calendar ORDER BY month ASC"
                Using da As New SqlDataAdapter(sql, sqlConn)
                    da.Fill(dt)
                End Using
            End Using
            MonthSearch.DataSource = dt
            MonthSearch.ValueMember = "month"
            MonthSearch.DisplayMember = "MonthName"

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        ' add the handler after populating the ComboBox to avoid unwanted firing of the event...
        AddHandler MonthSearch.SelectedIndexChanged, AddressOf MonthSearch_SelectedIndexChanged

    End Sub

    Private Sub MonthSearch_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim cb = DirectCast(sender, ComboBox)
        ' SelectedValue is an Object - you can get the name of its actual type with .SelectedValue.GetType().Name
        Dim val = CInt(cb.SelectedValue)
        MsgBox(val.ToString())

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SetUpMonthsCB()

    End Sub

End Class

The SelectedValueis returned as an object, but you can find its actual type with SelectedValue.GetType()- in this case it happened to be Byte, which can safely be converted to an Integer.

SelectedValue会返回一个对象,但你可以找到它的实际类型与SelectedValue.GetType()-在这种情况下,它碰巧是Byte,它可以安全地转换为Integer

You don't need a full DataSetfor the data - a DataTablewill suffice.

您不需要完整DataSet的数据 - 一个DataTable就足够了。

A DataAdapter will open and close the connection for you.

DataAdapter 将为您打开和关闭连接。

If you use Using, that will take care of disposing of objects for you.

如果您使用Using,它将为您处理对象。

If you want to have a handler reacting to the SelectedIndexChangedevent, it is better to add it after populating the ComboBox to avoid the event firing as the CB is populated.

如果您想让处理程序对SelectedIndexChanged事件做出反应,最好在填充 ComboBox 后添加它,以避免在填充 CB 时触发事件。

Incidentally, if you only need to populate the ComboBox with {1..12},{"January"..."December"}, you can use something like

顺便说一句,如果您只需要用 {1..12},{"January"..."December"} 填充 ComboBox,您可以使用类似

Dim dt = Enumerable.Range(1, 12).Select(Function(x) New With {.month = x, .MonthName = MonthName(x)}).ToList()
MonthSearch.DataSource = dt
MonthSearch.ValueMember = "month"
MonthSearch.DisplayMember = "MonthName"

回答by shadow

I guess the MsgBox(MonthSearch.SelectedValue.ToString)would do the work.

我想MsgBox(MonthSearch.SelectedValue.ToString)会做的工作。