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

时间:2013-08-06 15:05:32

标签: vb.net visual-studio-2010 web

我正在开发一段代码,允许我提取数据库的内容并将其显示在页面网页上。我正在使用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的情况下显示数据。

1 个答案:

答案 0 :(得分:0)

由于您没有定义gridview并且您无法更改ASPX标记,因此您在此处有多个其他选项,只有少数几个

  • 您可以以编程方式创建GridView控件并添加页面控件集合
  • 您可以在代码中构建ASP.NET Table并使用数据填充其单元格
  • 您可以使用StringBuilder使用输出构建HTML,然后输出结果

如果您确实需要声明“AuthorsGridView”gridview - 第一个选项适合您。

作为最基本的示例(您可能需要调整它,添加/修改gridview属性)替换行

AuthorsGridView.DataSource = ds
AuthorsGridView.DataBind()

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)
相关问题