今天刚学习了如何用ASP.NET连接ACCESS数据库并在DataGrid控件里显示出来。不看不知道,一看才发现有代码分离型的和代码与HTML放在一个页面型的。下面分别介绍一下这些最简单的连接数据库的方法:
一、不将代码放在单独的页面中
1.添加新项-WEB窗体-将代码放在单独的页面中(不打勾)
- <%@ Page Language="VB" ContentType="text/html" ResponseEncoding="utf-8" %>
- <%@ Import Namespace="System.Data" %>
- <%@ Import NameSpace="System.Data.OleDb" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Test - Access数据库连接</title>
- <script laguage="VB" runat="server">
- Dim myConnection As OleDbConnection
- Dim myCommand As OleDbCommand
- Sub page_load(ByVal Sender As Object, ByVal E As EventArgs)
- Dim dbname As String
- dbname = Server.MapPath("App_Data/chat.mdb")
- myConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DATA Source=" & dbname)
- myConnection.Open()
- myCommand = New OleDbCommand("Select ID,UserAcc,Password,NickName From [User] Order By ID Desc", myConnection)
- datagrid.DataSource = myCommand.ExecuteReader()
- datagrid.DataBind()
- myConnection.Close()
- End Sub
- </script>
- </head>
- <body>
- <ASP:DataGrid id="datagrid" runat="server"
- Width="100%"
- BackColor="white"
- BorderColor="black"
- ShowFooter="false"
- CellPadding="3"
- CellSpacing="0"
- Font-Name="Courier New, Courier, monospace"
- Font-Size="12px"
- HeaderStyle-BackColor="#aaaadd"
- MaintainState="false" />
- </body>
- </html>
二、将代码放在单独的页面中
1.添加新项-WEB窗体-将代码放在单独的页面中(打勾)
2.aspx:
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <ASP:DataGrid id="datagrid" runat="server"
- Width="100%"
- BackColor="white"
- BorderColor="black"
- ShowFooter="false"
- CellPadding="3"
- CellSpacing="0"
- Font-Name="Courier New, Courier, monospace"
- Font-Size="12px"
- HeaderStyle-BackColor="#aaaadd"
- MaintainState="false" />
- </div>
- </form>
- </body>
- </html>
2.aspx.vb
- Imports System.Data
- Imports System.Data.OleDb
- Partial Class _Default
- Inherits System.Web.UI.Page
- Dim myConnection As OleDbConnection
- Dim myCommand As OleDbCommand
- Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- Dim dbname As String
- dbname = Server.MapPath("App_Data/chat.mdb")
- myConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;DATA Source=" & dbname)
- myConnection.Open()
- myCommand = New OleDbCommand("Select ID,UserAcc,Password,NickName From [User] Order By ID Desc", myConnection)
- datagrid.DataSource = myCommand.ExecuteReader()
- datagrid.DataBind()
- myConnection.Close()
- End Sub
- End Class
两个查询的结果都是一样的,如下图所示: