retrieving data from SQL in VB (part 2)

瘦欲@ 提交于 2019-12-30 10:53:02

问题


I am trying to populate a listbox by retrieving data from a database through sql. I have asked this question earlier but i was using a different configuration and the one i'm using now isn't giving any results.

retrieving data in VB from SQL

That is my old post. I will now provide the code to the newer version of my attempt.

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

If anyone would be willing to help me out i'd greatly appreciate it. If possible, use a practical approach when trying to enlighten me, as that works best.

edit 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

With this code the listbox populates with 6 instances of "System.Data.DataRowView" strings, 6 being the number of items in my table. How do i get the actual values?


回答1:


You missed the connectionString
If you want to populate list from DB there are many ways

With 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

With 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


EDIT:
Other parameters of connection string depends on your security and all that. You must see this link Connection strings for SQL Server 2008




回答2:


Set the DisplayMember property after DataSource binding:

ListBox1.DataSource = dt
ListBox1.DisplayMember="name"



回答3:


The last solution I saw should work, but there are a couple important best practices to keep in mind regarding SQL Server.

1) Avoid Select * whenever possible, instead name your columns explicitly. Select * causes SQL to perform extra work if you do not intend to pull down all the columns in the table. It's also not future-proof, since a dba could add a VARBINARY(MAX) column in the future, and populate it with gigs worth of blob data, This scenario would make your query as written slow down substantially and unnecessarily.

2) Always remember to close your SQLConnection when you're done with it. This will free up a SQL connection and resources.

if (cn.State != ConnectionState.Closed)
cn.Close();

Another cool trick is to use the USING directive which will dispose of the SqlConnection object when execution passes out of scope.

using (SqlConnection cn = new SqlConnection(sConnectionString))
{
    if (cn.State != ConnectionState.Open)
    cn.Open();

   // add query code here.

    if (cn.State != ConnectionState.Closed)
    cn.Close();
}
  1. don't forget to close your SqlDataReader after the read loop is complete.

    if (!dr.IsClosed) dr.Close();

I hope this helps.

Andre Ranieri



来源:https://stackoverflow.com/questions/14917829/retrieving-data-from-sql-in-vb-part-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!