1

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

4

1 回答 1

0

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

  • 您可以以编程方式创建 GridView 控件并将其添加到页面控件集合
  • 您可以在代码中构建 ASP.NET 表并用数据填充其单元格
  • 您可以使用 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)
于 2013-08-06T15:11:59.927 回答