我正在按照教程从数据库中将数据插入到组合框中,但是即使DisplayMember正确显示,分配给ValueMember的所有数据似乎也是相同的。
这就是我将数据添加到组合框的方式
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都为零,我在代码中可能做错什么?
最佳答案
您使用的变量不正确。它应该是mID,而不是id。
Public Property id() As Integer
Get
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property
在VB.NET中,函数/属性的名称也用作返回值的某种变量。这与执行Return 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。无论如何,不要使用该功能,这会造成混乱。