Vb.net 提取数据库内容并将其显示在网站页面上

Vb.net 提取数据库内容并将其显示在网站页面上,vb.net,visual-studio-2010,web,Vb.net,Visual Studio 2010,Web,我正在开发一段代码,允许我提取数据库的内容并将其显示在网页上。我正在使用vb.net和SQLServer2008进行开发 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) Handl

我正在开发一段代码,允许我提取数据库的内容并将其显示在网页上。我正在使用vb.net和SQLServer2008进行开发

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的情况下显示数据。

因为您没有定义gridview,并且无法更改aspx标记,所以这里有多个其他选项,只有几个选项

您可以通过编程方式创建GridView控件,并将其添加到页面控件集合中 您可以用代码构建ASP.NET表,并用数据填充其单元格 您可以使用StringBuilder使用输出构建HTML,然后输出结果 如果您确实需要声明AuthorsGridView gridview-第一个选项适用于您

作为最基本的示例,您可能需要对其进行调整,添加/修改gridview属性替换线

AuthorsGridView.DataSource = ds
AuthorsGridView.DataBind()


不要以纯文本形式存储密码。尤其是永远不要显示密码。你的意思是你想显示查询结果,但你不想通过添加GridView来更改ASPX标记?@YuriyGalanter是的,这是我想要的,但我不知道怎么做我是asp.net的新手,请您解释一下好吗?我发现“GridView”类型的错误控件“AuthorsGridView”必须放在runat=server的表单标记中。对不起,我的错误。更新了最后一行,它应该是Me.Form.Controls.AddAuthorsGridViewI获取此错误对象引用未设置为对象的实例您将其标记为已应答,这是否意味着它对您有效?如果不是-哪一行导致错误?
Dim AuthorsGridView As New GridView

With AuthorsGridView
    .ID = "AuthorsGridView"
    .Width = Unit.Pixel(500)
    .AutoGenerateColumns = True
    .DataSource = ds
    .DataBind()
End With

Me.Form.Controls.Add(AuthorsGridView)