将数据从SQL显示到vb.net列表框

时间:2016-08-13 21:38:37

标签: vb.net

我试图将所有高尔夫球手的信息从TGolfers显示到ListBox中。但是当我运行我的代码时,它只显示一个高尔夫球手的信息。

Public Class frmGolfers

    Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

        Dim strSelect As String = ""
        Dim strName As String = ""
        Dim cmdSelect As OleDb.OleDbCommand ' this will be used for our Select statement
        Dim drSourceTable As OleDb.OleDbDataReader ' this will be where our data is retrieved to
        Dim dt As DataTable = New DataTable ' this is the table we will load from our reader

        ' open the database
        If OpenDatabaseConnectionSQLServer() = False Then

            ' No, warn the user ...
            MessageBox.Show(Me, "Database connection error." & vbNewLine & _
                                "The application will now close.",
                                Me.Text + " Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error)

            ' and close the form/application
            Me.Close()

        End If

        ' Build the select statement using PK from name selected
        strSelect = "SELECT * FROM TGolfers "

        ' Retrieve all the records 
        cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
        drSourceTable = cmdSelect.ExecuteReader

        ' load the data table from the reader
        dt.Load(drSourceTable)

        ' populate the text boxes with the data
        lbxDisplay.Items.Add(dt.Rows(0).Item(1).ToString & "," & " " & dt.Rows(0).Item(2).ToString &
                           ControlChars.CrLf & " " & dt.Rows(0).Item(3).ToString & " " & dt.Rows(0).Item(4).ToString & " " & dt.Rows(0).Item(5).ToString & " " & dt.Rows(0).Item(6).ToString)


        ' close the database connection
        CloseDatabaseConnection()

    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

加载DataTable后启动一个循环

......  
' load the data table from the reader
dt.Load(drSourceTable)

' populate the text boxes with the data
For Each row in dt.Rows
    Dim text = row(1).ToString & ", " & _
               row(2).ToString & ControlChars.CrLf & " " & _ 
               row(3).ToString & " " & _
               row(4).ToString & " " & _ 
               row(5).ToString & " " & _ 
               row(6).ToString
    lbxDisplay.Items.Add(text)
Next
......

通过这种方式,您遍历dt.Rows集合中的每一行,提取所需的信息,构建一个字符串并将该字符串添加到ListBox Items集合。

请注意,对于DataRow中的每一列,我都遵循从Index = 1开始的索引,但请记住,在.NET中,数组索引从索引0开始而不是1,因此数据行的第一列位于索引0处。根据需要更改代码中的索引。 (这意味着如果该表中有6列,则索引应该从0到5,在此方案中使用索引6会使索引超出范围异常)