DataGrid Learning Four

Source: Internet
Author: User
Tags zip
A few examples from the DataGrid have learned to read data from the database, so we learn to insert the data into the databases, add a simple input form to the page, and execute the Insert command in the form submission event handler. As with the first two examples, the value of the command is populated with the Parameters collection of the Command object. Note that before attempting to insert into the database, check to make sure that the value you want is not empty. This prevents accidental conflicts with the database's field constraints. You also need to execute the INSERT command inside the Try/catch block to prevent the primary key of the inserted row from already existing.



First look at the aspx file:
<body ms_positioning= "GridLayout" >
<form runat= "Server" id= "Form1" >
<table width= ">"
<tr>
&LT;TD valign= "Top" >
<asp:datagrid id= "Mydatagrid" runat= "Server" width= "backcolor=" "#ccccff" bordercolor= "Black" showfooter= " False "cellpadding=" 3 "cellspacing=" 0 "font-name=" "Song Body" font-size= "8pt" headerstyle-backcolor= "#aaaadd" Enableviewstate= "false"/>
</td>
&LT;TD valign= "Top" >
<table style= "font:9pt song body" >
<tr>
&LT;TD colspan= "2" bgcolor= "#aaaadd" style= "font:10.5pt song body" > Add new Author:</td>
</tr>
<tr>
&LT;TD nowrap> Author 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= "runat=" "Server" > *</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td nowrap> Surname:</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=" runat= "Server" > *</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
&LT;TD nowrap> name:</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=" runat= "Server" > *</asp:requiredfieldvalidator>
</td>
</tr>
<tr>
<td> Telephone:</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= "runat=" "Server" > *</asp:requiredfieldvalidator></nobr>
</td>
</tr>
<tr>
<td> Address:</td>
<td><input type= "text" id= "address" value= "one Microsoft Way" runat= "Server" name= "Address" ></td>
</tr>
<tr>
<td> City:</td>
<td><input type= "text" id= "City" value= "Redmond" runat= "Server" name= "City" ></td>
</tr>
<tr>
<td> State:</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>
&LT;TD nowrap> zip code:</td>
<td><input type= "text" id= "Zip" value= "98005" runat= "server" name= "Zip" ></td>
</tr>
<tr>
<td> Agreement:</td>
<td>
<select id= "Contract" runat= "Server" name= "contract" >
<option value= "0" selected> fake </option>
<option value= "1" > True </option>
</select>
</td>
</tr>
<tr>
<td></td>
&LT;TD style= "padding-top:15px" >
<input type= "Submit" value= "add Author" runat= "Server" id= "Submit1" name= "Submit1" >
</td>
</tr>
<tr>
&LT;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= "runat=" Server ">* zip code must be 5 digits <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=" one "runat=" server ">* phone number format must be: XXX xxx-xxxx < br></asp:regularexpressionvalidator> <asp:regularexpressionvalidator id= "Au_idRegexVal" ControlToVal Idate= "au_id" validationexpression= "[0-9]{3}-[0-9]{2}-[0-9]{4}" display= "Dynamic" font-name= "Arial" font-size= "11" runat= "Server" >* author ID must be a number: Xxx-xx-xxxx <br></asp:RegularExpressionValidator></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>



Aspx.cs file
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>
Summary description of the 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: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</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 (@i D, @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> added record </b><br>" + Insertcmd + "<p>";
}
catch (SqlException ex)
{
if (ex. Number = 2627)
message.innerhtml = "Error: Record with same primary key already exists <p>";
Else
message.innerhtml = "Error: Failed to add record, make sure the field <p>" is filled in correctly;
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 ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.