我试图通过sql从数据库中检索数据来填充列表框.我之前已经问过这个问题,但我使用的是不同的配置,而我现在使用的配置并没有给出任何结果.
retrieving data in VB from SQL
那是我的老帖子.我现在将为我的尝试的新版本提供代码.
Imports System.Data.sql Imports System.Data.sqlClient Public Class Form1 Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load Dim conn As New sqlConnection conn.Open() Dim comm As New sqlCommand("SELECT name FROM Table_1",conn) Dim reader As sqlDataReader = comm.ExecuteReader Dim dt As New DataTable dt.Load(reader) ListBox1.Items.Add(dt) End Sub End Class
如果有人愿意帮助我,我会非常感激.如果可能的话,在试图启发我时使用实用的方法,因为这是最好的.
编辑1
Imports System.Data.sql Imports System.Data.sqlClient Public Class Form1 Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load Dim connString As String = "Data Source=THE_SHOGUNATE\sqlEXPRESS;Initial Catalog=le_database;Integrated Security=True" Dim conn As New sqlConnection(connString) conn.Open() Dim comm As New sqlCommand("SELECT name FROM Table_1",conn) Dim reader As sqlDataReader = comm.ExecuteReader Dim dt As New DataTable dt.Load(reader) ListBox1.DataSource = dt End Sub End Class
使用此代码,列表框将填充6个“System.Data.DataRowView”字符串实例,其中6个是我表中的项目数.我如何获得实际值?
解决方法
你错过了connectionString
如果要从DB填充列表,有很多方法
使用DataReader
Imports System.Data.sql Imports System.Data.sqlClient Public Class Form1 Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load Dim connectionString As String = "Data Sourec=localhost;........." Dim conn As New sqlConnection(connectionString) conn.Open() Dim comm As New sqlCommand("SELECT name FROM Table_1",conn) Dim reader As sqlDataReader = comm.ExecuteReader /* As it is not working i commented this listBox1.ItemsSource = dt; // use this instead of ListBox1.Items.Add(dt) //because Add event add only one item in the list. */ Dim i As Integer i=0 while reader.read() listBox1.Items.Add(dr(i).ToString); i++ End While End Sub End Class
使用DataTable
Imports System.Data.sql Imports System.Data.sqlClient Public Class Form1 Private Sub Form1_Load(sender As Object,e As EventArgs) Handles MyBase.Load Dim connectionString As String = "Data Sourec=localhost;........." Dim conn As New sqlConnection(connectionString) conn.Open() // Create new DataAdapter sqlDataAdapter a = new sqlDataAdapter("SELECT * FROM EmployeeIDs",c) // Use DataAdapter to fill DataTable DataTable dt = new DataTable(); a.Fill(dt); ListBox1.DataSource = dt; ListBox1.DataTextField = "name"; End Sub End Class
编辑:
连接字符串的其他参数取决于您的安全性以及所有这些.你必须看到这个链接Connection strings for SQL Server 2008