自由之声论坛

首页 » 学习园地 » 数字家园 » 编程园地 » GridView.DataBind 方法 ()的VB.NET例子
山谷 - 2008-1-14 16:20:00
<%@ Page language="VB" %> 
<%@ import namespace="System.Data" %> 
<%@ import namespace="System.Data.SqlClient" %> 
 
<SCRIPT runat="server"> 
 
  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 
     
    ' This example uses Microsoft SQL Server and connects 
    ' to the Northwind sample database. The data source needs 
    ' to be bound to the GridView control only when the 
    ' page is first loaded. Thereafter, the values are 
    ' stored in view state.                       
    If Not IsPostBack Then 
         
      ' Declare the query string. 
      Dim queryString As String = _ 
        "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]" 
         
      ' Run the query and bind the resulting DataSet 
      ' to the GridView control. 
      Dim ds As DataSet = GetData(queryString) 
      If (ds.Tables.Count > 0) Then 
       
        Authors<a href="http://www.wewill.cn/search.aspx?Where=Nkey&Keyword=GridView" title="GridView">GridView</a>.DataSource = ds 
        AuthorsGridView.DataBind() 
       
      Else 
       
        Message.Text = "Unable to connect to the database." 
         
      End If 
             
    End If 
     
  End Sub 
     
  Function GetData(ByVal queryString As String) As <a href="http://www.wewill.cn/search.aspx?Where=Nkey&Keyword=DataSet" title="DataSet">DataSet</a> 
     
    ' Retrieve the connection string stored in the Web.config file. 
    Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthWindConnectionString").ConnectionString 
 
    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." 
         
    End Try 
         
    Return ds 
         
  End Function 
     
</SCRIPT> 
 
<HTML> 
   
    <FORM runat="server"> 
         
      <H3>GridView DataBind Example</H3> 
             
      <ASP:LABEL id=Message runat="server" forecolor="Red" /> 
                 
      <BR>     
 
      <ASP:GRIDVIEW id=AuthorsGridView runat="server" autogeneratecolumns="true"> 
      </ASP:GRIDVIEW> 
                         
    </FORM>
1
查看完整版本: GridView.DataBind 方法 ()的VB.NET例子