資料庫連線類別 (myconn.cs)
namespace notpage
{
using System.Data.SqlClient;
public class myconn : SqlConnection
{
public myconn()
{
this.Database = "back";
this.DataSource = "LUOCHANG";
this.UserID = "sa";
this.Password = "";
}
}
}
新增留言頁面 (addTopic.aspx)
<%@ Page Language="c#" Codebehind="AddTopic.cs" AutoEventWireup="false" Inherits="notpage.AddTopic" %>
<html><head>
<meta name="GENERATOR" content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" content="C#"></head>
<body>
<form method="post" runat="server">
<table cellspacing="1" cellpadding="1" width="88%" border="0">
<tr><td>留言主題:</td>
<td><asp:TextBox id="txtTitle" runat="server" MaxLength="80" Columns="65"></asp:TextBox></td></tr>
<tr><td>姓名:</td>
<td><asp:TextBox id="txtAuthor" runat="server" MaxLength="40" Columns="20"></asp:TextBox></td></tr>
<tr><td>留言內容</td>
<td><asp:TextBox id="txtContent" runat="server" MaxLength="2000" Columns="50" Rows="20" TextMode="MultiLine"></asp:TextBox>
<asp:Button id="btnSubmit" runat="server" Text="確認"></asp:Button></td></tr>
</table></form>
</body></html>
後端邏輯 (AddTopic.cs)
namespace notpage
{
using System;
using System.Web.UI.WebControls;
public class AddTopic : System.Web.UI.Page
{
protected TextBox txtContent, txtAuthor, txtTitle;
protected Button btnSubmit;
public AddTopic()
{
Page.Init += Page_Init;
}
protected void Page_Load(object sender, EventArgs e) { }
protected void Page_Init(object sender, EventArgs e)
{
InitializeComponent();
}
private void InitializeComponent()
{
btnSubmit.Click += OnSubmit;
this.Load += Page_Load;
}
public void OnSubmit(object sender, EventArgs e)
{
if (Page.IsValid)
{
try
{
notepage objNp = new notepage();
objNp.Title = txtTitle.Text;
objNp.Author = txtAuthor.Text;
objNp.Content = txtContent.Text;
objNp.AddDate = DateTime.Now;
notepage objNp1 = new notepage();
if (objNp1.AddTopic(objNp))
{
Response.Write("<p align=center>成功留言,點擊<a href='list.aspx'>此處</a>查看留言列表!</p>");
}
}
catch (Exception exp)
{
#if DEBUG
Response.Write("出現異常:" + exp.Message);
return;
#endif
}
}
}
}
}
關鍵技術點
- 繼承
SqlConnection 封裝連線字串(myconn 類別)。
- 使用
asp:TextBox (MultiLine) 與 asp:Button 進行表單輸入。
- 按鈕點擊事件
OnSubmit 中建立實體物件並呼叫資料存取層 AddTopic()。
- 除錯模式下直接輸出例外訊息,正式環境靜默處理。