2013-08-06 97 views
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的情況下顯示數據。

+0

**不要將密碼存放在純文本** 。 _Especially_不會顯示密碼。 – SLaks

+0

你的意思是你想顯示查詢結果,但你不想通過添加GridView來改變ASPX標記? –

+0

@YuriyGalanter是的,這是我想要的,但我不知道該怎麼做 – user2649088

回答

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) 
+0

我是一個新的asp.net,請你可以解釋一下嗎? – user2649088

+0

@ user2649088更新了我的回答 –

+0

我得到這個錯誤「Control'AuthorsGridView'類型'GridView'必須放置在runat = server的表單標籤內。」 – user2649088

相關問題