后台代码: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = ""; } protected void Button1_Click(object sender, EventArgs e) { string text = TextBox1.Text; if (Hidden1.Value == "1") { if (returnString("insert into student select '" + text + "'") == "1") { Label1.Text = text + "保存成功"; } else { Label1.Text = text + "保存失敗"; } Hidden1.Value = "0"; TextBox1.Text = ""; } else { string tt = ""; if (text.Trim() == "") { tt = "alert('不要提交空值!')"; } else { DataSet ds = new DataSet(); ds = returnDS("select count(1) from student where username='" + text + "'"); string content = text + "在資料庫中的個數為:" + ds.Tables[0].Rows[0][0].ToString() + ",確定保存?"; tt = "var rs=window.confirm(/" " + content + " /");"; tt += "if(rs){document.getElementById(/"" + Hidden1.ClientID + "/").value=/"1/";document.getElementById(/"" + Button1.ClientID + "/").click(); }else{ };"; } this.Page.RegisterStartupScript("aa", "<mce:script ><!-- " + tt + " // --></mce:script>"); } } public DataSet returnDS(string sql) { string connstr = "Data Source=xxxx;initial catalog=xxxx;user id=xxxx;password=xxxx"; SqlConnection myconn = new SqlConnection(connstr); myconn.Open(); SqlCommand mycomm = new SqlCommand(); mycomm.Connection = myconn; mycomm.CommandText = sql; mycomm.CommandType = CommandType.Text; SqlDataAdapter da = new SqlDataAdapter(mycomm); DataSet ds = new DataSet(); da.Fill(ds, "table"); myconn.Close(); return ds; } public string returnString(string sql) { try { string connstr = "Data Source=xxxx;initial catalog=xxxx;user id=xxxx;password=xxxx"; SqlConnection myconn = new SqlConnection(connstr); myconn.Open(); SqlCommand mycomm = new SqlCommand(); mycomm.Connection = myconn; mycomm.CommandText = sql; mycomm.CommandType = CommandType.Text; mycomm.ExecuteNonQuery(); myconn.Close(); return "1"; } catch (Exception ex) { return "2"; } } } 前台代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> <input id="Hidden1" runat="server" style="width: 14px" type="hidden" /> <asp:Label ID="Label1" runat="server"></asp:Label></div> </form> <div id="aa"></div> </body> </html>