当前位置 : 主页 > 编程语言 > c语言 >

vb.net – 在VB中从SQL检索数据(第2部分)

来源:互联网 收集:自由互联 发布时间:2021-06-24
我试图通过sql从数据库中检索数据来填充列表框.我之前已经问过这个问题,但我使用的是不同的配置,而我现在使用的配置并没有给出任何结果. retrieving data in VB from SQL 那是我的老帖子
我试图通过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

网友评论