DataGrid學習四

來源:互聯網
上載者:User
datagrid 前面幾個例子學習了從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:RegularExpressionValidator>
<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 Form設計器所必需的。
   //
   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();
  }
}
}

相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。