gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:41:31 25 4
gpt4 key购买 nike

我试图通过 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
如果你想从数据库填充列表,有很多方法

使用 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

使用数据表

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

关于vb.net - 在 VB 中从 SQL 检索数据(第 2 部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14917829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com