今天给大家讲述一个怎样用ASP.NET来编写一个简单的留言本程序(下面为具体步骤和代码),本例子的目的是让大家掌握ASP.NET编程技术的实现方法,只要把下面的代码看懂,再加上你自己把页面美化或把数据库中的内容再添加详细一些,就会得到一个很好的留言本。你有什么问题请进论坛发表见解。
1、用Access建造一个数据库data.mdb,建立表Guest,结构如下:
ID 自动编号 标题 字符串 署名 字符串 正文 备注。
2、guest.aspx <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <html><head> <style> <!-- body{font-size:9pt} p{font-size:9pt} td{font-size:9pt} --> </style> <title>留言本</title></head> <body> <p align=right><font size=6>留言本</font></p> <script language=vb runat=server> Sub Page_Load(Source As Object, E As EventArgs) Dim myConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=" & server.mappath("data.mdb")) Dim myAdapter As New OleDbDataAdapter Dim myOleDbCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(myAdapter) Dim DS As DataSet = New DataSet myAdapter.SelectCommand = new OleDbCommand("select ID, 标题, 署名 from Guest order by id desc", myconn) myconn.open() myAdapter.Fill(ds, "Guest") ml.DataSource=ds.Tables("Guest").DefaultView ml.DataBind() end sub </script> <ASP:DataGrid id="ml" runat="server" Width="100%" BorderColor="black" ShowFooter="false" CellPadding=3 CellSpacing="0" Font-Name="宋体" Font-Size="9pt" HeaderStyle-BackColor="#ddaacc" EnableViewState="false" > <Columns> <asp:HyperLinkColumn DataNavigateUrlField="id" DataNavigateUrlFormatString="see.asp?id={0}" text="See!" Target="_new" /> </Columns> </asp:DataGrid> <br><br><font size=5>我要留言</font><br> <form method=post action=send.aspx> 标题:<input type=text name=title><br> 署名:<input type=text name=name><br> 内容:<textarea name=body></textarea><br> <input type=submit> </form>
3、send.aspx <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.OleDb" %> <script language=vb runat=server> Sub Page_Load(Source As Object, E As EventArgs) Dim myConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=" & server.mappath("data.mdb")) Dim myInsertQuery As String = "insert into guest (标题, 署名, 内容) values ('" & request("title") & "', '" & request("name") & "', '" & request("body") & "')" Dim myOleDbCommand As New OleDbCommand(myInsertQuery) myOleDbCommand.Connection = myConn myConn.Open() myOleDbCommand.ExecuteNonQuery() myOleDbCommand.Connection.Close() response.redirect("guest.aspx") end sub </script>
4、see.asp(显示单个数据不如用ASP) <html><head> <style> <!-- body{font-size:9pt} p{font-size:9pt} td{font-size:9pt} file://--> </style> <title>察看留言</title></head> <body> <p align=right><font size=6>察看留言</font></p> <% id=request("id") set cn=server.createobject("ADODB.CONNECTION") cn.open "DBQ=" + server.mappath("data.mdb") + ";DefaultDir=; DRIVER={Microsoft Access Driver (*.mdb)};" set rs=server.createobject("adodb.recordset") rs.open "select * from guest where id=" & id , cn %> ID:<% = id %><BR> 标题:<% = rs("标题") %><br> 署名:<% = rs("署名") %><br> 内容:<Br><% = rs("内容") %><br> <a href="guest.aspx">返回</a>
|