我正在开发一段代码,允许我提取数据库的内容并将其显示在网页上。我正在使用 vb.net 和 sql server 2008 进行开发。
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Declare the query string.
Dim queryString As String = _
"Select [id], [username], [password] From [userTD]"
' Run the query and bind the resulting DataSet
' to the GridView control.
Dim ds As DataSet = GetData(queryString)
If (ds.Tables.Count > 0) Then
AuthorsGridView.DataSource = ds
AuthorsGridView.DataBind()
Else
' Message.Text = "Unable to connect to the database."
Response.Write("<br>Unable to connect to the database.")
End If
End If
End Sub
Function GetData(ByVal queryString As String) As DataSet
' Retrieve the connection string stored in the Web.config file.
Dim connectionString As String
connectionString = ("Data Source=mypc-PC;Database=mytempDB;Integrated Security=true ")
Dim ds As New DataSet()
Try
' Connect to the database and run the query.
Dim connection As New SqlConnection(connectionString)
Dim adapter As New SqlDataAdapter(queryString, connection)
' Fill the DataSet.
adapter.Fill(ds)
Catch ex As Exception
' The connection failed. Display an error message.
' Message.Text = "Unable to connect to the database."
Response.Write("<br>Unable to connect to the database.")
End Try
Return ds
End Function
End Class
代码工作正常。就我而言,我必须在 default.aspx 中声明“AuthorsGridView”,但我的目标是在不修改 default.aspx 的情况下显示数据。