前面几个例子学习了从DataBase里面读数据,下面我们学习将数据插入到数据库中
,可以向页中添加简单的输入窗体,并在窗体提交事件处理程序中执行插入命令。与前
两个示例一样,使用命令对象的 Parameters 集合填充命令的值。注意,在试图插入到
数据库中之前,还要检查以确保所需的值非空。这将防止与数据库的字段约束意外冲突
。还需在 try/catch 块的内部执行插入命令,以防插入行的主键已经存在。
先看aspx文件:
<body MS_POSITIONING="GridLayout">
<form runat="server" ID="Form1">
<h3><font face="宋体">插入具有验证的数据行</font></h3>
<table width="95%">
<tr>
<td valign="top">
<ASP:DataGrid id="MyDataGrid" runat="server" Width="700" BackColor="#ccccff"
BorderColor="black" ShowFooter="false" CellPadding="3" CellSpacing="0"
Font-Name="宋体" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd"
EnableViewState="false" />
</td>
<td valign="top">
<table style="FONT: 9pt 宋体">
<tr>
<td colspan="2" bgcolor="#aaaadd" style="FONT:10.5pt 宋体">添加新作者:</td>
</tr>
<tr>
<td nowrap>作者 ID:</td>
<td>
<input type="text" id="au_id" value="000-00-0000" runat="server"
NAME="au_id">
<asp:RequiredFieldValidator id="au_idReqVal" ControlToValidate="au_id"
Display="Static" Font-Name="Verdana" Font-Size="12"
runat="server"> *</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td nowrap>姓氏:</td>
<td>
<input type="text" id="au_lname" value="Doe" runat="server" NAME="au_lname">
<asp:RequiredFieldValidator id="au_lnameReqVal"
ControlToValidate="au_lname" Display="Static" Font-Name="Verdana"
Font-Size="12" runat="server"> *</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td nowrap>名字:</td>
<td>
<input type="text" id="au_fname" value="John" runat="server"
NAME="au_fname">
<asp:RequiredFieldValidator id="au_fnameReqVal"
ControlToValidate="au_fname" Display="Static" Font-Name="Verdana"
Font-Size="12" runat="server"> *</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>电话:</td>
<td><nobr> <input type="text" id="phone" value="808 555-5555"
runat="server" NAME="phone">
<asp:RequiredFieldValidator id="phoneReqVal" ControlToValidate="phone"
Display="Static" Font-Name="Verdana" Font-Size="12"
runat="server"> *</asp:RequiredFieldValidator></nobr>
</td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" id="address" value="One Microsoft Way"
runat="server" NAME="address"></td>
</tr>
<tr>
<td>城市:</td>
<td><input type="text" id="city" value="Redmond" runat="server"
NAME="city"></td>
</tr>
<tr>
<td>州:</td>
<td>
<select id="state" runat="server" NAME="state">
<option selected>CA</option>
<option>IN</option>
<option>KS</option>
<option>MD</option>
<option>MI</option>
<option>OR</option>
<option>TN</option>
<option>UT</option>
</select>
</td>
</tr>
<tr>
<td nowrap>邮政编码:</td>
<td><input type="text" id="zip" value="98005" runat="server"
NAME="zip"></td>
</tr>
<tr>
<td>协定:</td>
<td>
<select id="contract" runat="server" NAME="contract">
<option value="0" selected>假</option>
<option value="1">真</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td style="PADDING-TOP:15px">
<input type="submit" value="添加作者" runat="server" ID="Submit1"
NAME="Submit1">
</td>
</tr>
<tr>
<td colspan="2" style="PADDING-TOP:15px" align="middle">
<span id="Message" EnableViewState="false" runat="server">
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ASPClass="RegularExpressionValidator" ControlToValidate="zip"
ValidationExpression="[0-9]{5}" Display="Dynamic" Font-Name="Arial"
Font-Size="11" runat="server">* 邮政编码必须是 5 位数字<br></asp:RegularExpre
ssionValidator>
<asp:RegularExpressionValidator id="phoneRegexVal"
ControlToValidate="phone" ValidationExpression="[0-9]{3} [0-9]{3}-[0-9]{4}"
Display="Dynamic" Font-Name="Arial" Font-Size="11" runat="server">* 电话号码
格式必须为:XXX XXX-XXXX <br></asp:RegularExpressionValidator>
<asp:RegularExpressionValidator id="au_idRegexVal"
ControlToValidate="au_id" ValidationExpression="[0-9]{3}-[0-9]{2}-[0-9]{4}"
Display="Dynamic" Font-Name="Arial" Font-Size="11" runat="server">* 作者 ID
必须是数字:XXX-XX-XXXX <br></asp:RegularExpressionValidator></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
aspx.cs文件
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace study
{
/// <summary>
/// datagrid_5 的摘要说明。
/// </summary>
public class datagrid_5 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid MyDataGrid;
protected System.Web.UI.WebControls.RequiredFieldValidator au_idReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator au_lnameReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator au_fnameReqVal;
protected System.Web.UI.WebControls.RequiredFieldValidator phoneReqVal;
protected System.Web.UI.WebControls.RegularExpressionValidator
RegularExpressionValidator1;
protected System.Web.UI.WebControls.RegularExpressionValidator
phoneRegexVal;
protected System.Web.UI.WebControls.RegularExpressionValidator
au_idRegexVal;
protected System.Web.UI.HtmlControls.HtmlInputText au_id;
protected System.Web.UI.HtmlControls.HtmlInputText au_lname;
protected System.Web.UI.HtmlControls.HtmlInputText au_fname;
protected System.Web.UI.HtmlControls.HtmlInputText phone;
protected System.Web.UI.HtmlControls.HtmlInputText address;
protected System.Web.UI.HtmlControls.HtmlInputText city;
protected System.Web.UI.HtmlControls.HtmlSelect state;
protected System.Web.UI.HtmlControls.HtmlInputText zip;
protected System.Web.UI.HtmlControls.HtmlSelect contract;
protected System.Web.UI.HtmlControls.HtmlInputButton Submit1;
protected System.Web.UI.HtmlControls.HtmlGenericControl Message;
SqlConnection myConnection;
private void Page_Load(object sender, System.EventArgs e)
{
myConnection = new SqlConnection("user id=sa;password=;initial
catalog=pubs;data source=jeff");
if (!IsPostBack)
BindGrid();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Submit1.ServerClick += new
System.EventHandler(this.Submit1_ServerClick);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Submit1_ServerClick(object sender, System.EventArgs e)
{
Message.InnerHtml = "";
if (Page.IsValid)
{
String insertCmd = "insert into Authors (au_id, au_lname, au_fname,
phone, address, city, state, zip, contract) values (@Id, @LName, @FName,
@Phone, @Address, @City, @State, @Zip, @Contract)";
SqlCommand myCommand = new SqlCommand(insertCmd, myConnection);
myCommand.Parameters.Add(new SqlParameter("@Id", SqlDbType.NVarChar,
11));
myCommand.Parameters["@Id"].Value = au_id.Value;
myCommand.Parameters.Add(new SqlParameter("@LName", SqlDbType.NVarChar,
40));
myCommand.Parameters["@LName"].Value = au_lname.Value;
myCommand.Parameters.Add(new SqlParameter("@FName", SqlDbType.NVarChar,
20));
myCommand.Parameters["@FName"].Value = au_fname.Value;
myCommand.Parameters.Add(new SqlParameter("@Phone", SqlDbType.NChar,
12));
myCommand.Parameters["@Phone"].Value = phone.Value;
myCommand.Parameters.Add(new SqlParameter("@Address",
SqlDbType.NVarChar, 40));
myCommand.Parameters["@Address"].Value = address.Value;
myCommand.Parameters.Add(new SqlParameter("@City", SqlDbType.NVarChar,
20));
myCommand.Parameters["@City"].Value = city.Value;
myCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NChar,
2));
myCommand.Parameters["@State"].Value = state.Value;
myCommand.Parameters.Add(new SqlParameter("@Zip", SqlDbType.NChar, 5));
myCommand.Parameters["@Zip"].Value = zip.Value;
myCommand.Parameters.Add(new SqlParameter("@Contract",
SqlDbType.NVarChar,1));
myCommand.Parameters["@Contract"].Value = contract.Value;
myCommand.Connection.Open();
try
{
myCommand.ExecuteNonQuery();
Message.InnerHtml = "<b>已添加记录</b><br>" + insertCmd + "<p>";
}
catch (SqlException ex)
{
if (ex.Number == 2627)
Message.InnerHtml = "错误:已存在具有相同主键的记录<p>";
else
Message.InnerHtml = "错误:未能添加记录,请确保正确填写了字段<p>";
Message.Style["color"] = "red";
}
myCommand.Connection.Close();
}
BindGrid();
}
public void BindGrid()
{
SqlDataAdapter myCommand = new SqlDataAdapter("select * from Authors",
myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
MyDataGrid.DataSource=ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
}
}