我这里有代码查询数据库以根据全名提供用户列表。问题是,当我将列表分配给一个变量时,稍后我将该变量分配给一个列表框,它只显示一个结果。有人可以帮我吗?
Private ListofAllUsers As String
Private Sub GetALLUserList()
Dim UFullNameList As String
If DataConnection.State = ConnectionState.Open Then
Try
QueryConnect = "SELECT * From users"
CommandConnect = New MySqlCommand(QueryConnect, DataConnection)
MyDataConnect = CommandConnect.ExecuteReader
While MyDataConnect.Read()
UFullNameList = MyDataConnect.GetString("FullName")
ListofAllUsers = (UFullNameList)
End While
MyDataConnect.Close()
Catch ex As MySqlException
MsgBox(ex.Message, CType(MessageBoxIcon.Error, MsgBoxStyle), LoginUI.BrandMsgBox)
DataConnection.Close()
End Try
Else
Call GetSoftwareData()
'Retry Again
GetALLUserList()
End If
现在我这样做它只显示一个有人可以帮助我吗?
UListBox.Items.Add(ListofAllUsers)
最佳答案
将 ListofAllUsers
声明为 List (Of String)
在 while 循环中,只需将项目添加到字符串列表中即可。
我还添加了 using
block 来正确处理连接。
Private ListofAllUsers As New List (Of String)
Private Sub GetALLUserList()
Dim UFullNameList As String
Dim QueryConnect = "SELECT * From users"
'Add using block to properly dispose stuff.'
Using DataConnection As New SqlConnection("your connection string"),
cmd As New SqlCommand(QueryConnect, DataConnection)
DataConnection.Open()
Try
Dim MyDataConnect As SqlDataReader = cmd.ExecuteReader()
While MyDataConnect.Read()
UFullNameList = MyDataConnect.GetString("FullName")
'Add the item to the list of string here'
ListofAllUsers.Add(UFullNameList)
End While
Catch ex As MySqlException
MsgBox(ex.Message, CType(MessageBoxIcon.Error, MsgBoxStyle), LoginUI.BrandMsgBox)
End Try
DataConnection .Close()
End Using
End Sub
然后您可以将项目添加到列表框中,如下所示:
UListBox.Items.AddRange(ListofAllUsers)
关于mysql - VB.Net 列出 MySQL 中的所有用户并将它们分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889236/