2016-08-13 28 views
-1

TGolfersからのすべてのゴルファーの情報をListBoxに表示しようとしています。しかし、自分のコードを走らせると、ゴルファーの情報が1つしか表示されません。SQLからvb.netへのデータ表示リストボックス

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 
+0

リストボックスの項目に追加するためDataTableの最初の行(行(0))で、完全なデータテーブルではありません。あなたはループを書く必要があります(foreachのためのIE |たくさんの選択肢があります) – Steve

+0

お返事ありがとうございます! –

+0

これは私が使ったループです。このエラーは "位置0に行がありません" Dim count As Integer count = 0 drSourceTable.Read中に count = count + 1 終了中 –

答えて

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から始まらないことに注意してください。したがって、datarowの最初の列はインデックス0必要に応じてコード内のインデックスを変更します。 (つまり、このテーブルに6列ある場合、インデックスは0から5になるはずです。このシナリオでインデックス6を使用すると、インデックス外の例外が発生します)

+0

あなたは私の一日を作ったばかりです!どうもありがとうございました! –

関連する問題