为什么cmbstream.valuemember=“id”所有值都显示为零,而cmbstream.displaymember=“name”却显示正确的值

qgelzfjb  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(204)

我按照一个教程将数据从数据库插入到组合框中,但似乎分配给所有数据的valuemember是相同的,即使displaymember显示正确。
这就是我将数据添加到组合框的方式

Private Sub cmbStream_VisibleChanged(sender As Object, e As EventArgs) Handles cmbStream.VisibleChanged
    If cmbStream.Visible = True Then
        cmbStream.DataSource = GetStreamItems()
        cmbStream.DisplayMember = "name"
        cmbStream.ValueMember = "id"
    End If
End Sub

在得到这样的数据之后

Function GetStreamItems() As List(Of StreamItem)
    Dim streamItems = New List(Of StreamItem)
    Dim reader As MySqlDataReader
    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString = "server='" & My.Settings.MServer & "';user='" & My.Settings.MDbUser & "';password='" & My.Settings.MDbPass & "';database='" & My.Settings.MDb & "'"
    Dim sql As String = "SELECT id, name FROM tbl_streams"
    Dim Command As MySqlCommand
    MysqlConn.Open()
    Command = New MySqlCommand(sql, MysqlConn)
    Command.CommandTimeout = 30
    reader = Command.ExecuteReader()
    If reader.HasRows = True Then
        While reader.Read()
            streamItems.Add(New StreamItem(reader("id"), reader("name")))
        End While
    End If
    Return streamItems
End Function

下面是streamitem类

Public Class StreamItem
    Public Sub New(ByVal id As Integer, ByVal name As String)
        mID = id
        mName = name
    End Sub

    Private mID As Integer
    Public Property id() As Integer
        Get
            Return id
        End Get
        Set(ByVal value As Integer)
            mID = value
        End Set
    End Property

    Private mName As String
    Public Property name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property
End Class

在代码中将所有数据的valuemember设置为零时,我可能做错了什么?

mzsu5hc0

mzsu5hc01#

您没有为get使用正确的变量。它应该在中间,而不是id。

Public Property id() As Integer
    Get
        Return mID
    End Get
    Set(ByVal value As Integer)
        mID = value
    End Set
End Property

在vb.net中,函数/属性的名称也用作返回值的某种变量。这与返回123相同

Function SomeFunc() As Integer
    SomeFunc = 123
End Function

或者你的情况呢

Public Property id() As Integer
    Get
        id = mID
    End Get
    Set(ByVal value As Integer)
        mID = value
    End Set
End Property

由于尚未设置id,因此默认值为0。不管怎样,不要使用这个功能,这很混乱。

相关问题