Insert, update and delete (C#) : SqlServer « ADO.net Database « ASP.NET Tutorial

ASP.NET Tutorial
1. ASP.Net Instroduction
2. Language Basics
3. ASP.net Controls
4. HTML Controls
5. Page Lifecycle
6. Response
7. Collections
8. Validation
9. Development
10. File Directory
11. Sessions
12. Cookie
13. Cache
14. Custom Controls
15. Profile
16. Configuration
17. LINQ
18. ADO.net Database
19. Data Binding
20. Ajax
21. Authentication Authorization
22. I18N
23. Mobile
24. WebPart
25. XML
Java
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
ASP.NET Tutorial » ADO.net Database » SqlServer 
18. 42. 8. Insert, update and delete (C#)
File: Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AuthorManager" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
      <br />
      <asp:Label id="Label1" runat="server">Select Author:</asp:Label>
      <asp:DropDownList id="lstAuthor" runat="server" AutoPostBack="True" onselectedindexchanged="lstAuthor_SelectedIndexChanged"></asp:DropDownList>&nbsp;&nbsp;&nbsp;
      <asp:Button id="cmdUpdate" runat="server" Text="Update" onclick="cmdUpdate_Click"></asp:Button>&nbsp;
      <asp:Button id="cmdDelete" runat="server" Text="Delete" onclick="cmdDelete_Click"></asp:Button>
      <br />
      <asp:Label id="Label11" runat="server" Width="99px" Height="19px">Or:</asp:Label>
      <asp:Button id="cmdNew" runat="server" Width="91px" Height="24px" Text="Create New" onclick="cmdNew_Click"></asp:Button>&nbsp;
      <asp:Button id="cmdInsert" runat="server" Width="85px" Height="24px" Text="Insert New" onclick="cmdInsert_Click"></asp:Button>
    </div>
    <br />
    <div>
      <asp:Label id="Label10" runat="server" Width="100px">Unique ID:</asp:Label>
      <asp:TextBox id="txtID" runat="server" Width="184px"></asp:TextBox>&nbsp; 
      (required:&nbsp;###-##-#### form)<br />
      
      <asp:Label id="Label2" runat="server" Width="100px">First Name:</asp:Label>
      <asp:TextBox id="txtFirstName" runat="server" Width="184px"></asp:TextBox><br />
      
      <asp:Label id="Label3" runat="server" Width="100px">Last Name:</asp:Label>
      <asp:TextBox id="txtLastName" runat="server" Width="183px"></asp:TextBox><br />
      
      <asp:Label id="Label4" runat="server" Width="100px">Phone:</asp:Label>
      <asp:TextBox id="txtPhone" runat="server" Width="183px"></asp:TextBox><br />
      
      <asp:Label id="Label5" runat="server" Width="100px">Address:</asp:Label>
      <asp:TextBox id="txtAddress" runat="server" Width="183px"></asp:TextBox><br />
      
      <asp:Label id="Label6" runat="server" Width="100px">City:</asp:Label>
      <asp:TextBox id="txtCity" runat="server" Width="184px"></asp:TextBox><br />
      
      <asp:Label id="Label7" runat="server" Width="100px">State:</asp:Label>
      <asp:TextBox id="txtState" runat="server" Width="184px"></asp:TextBox><br />
      
      <asp:Label id="Label9" runat="server" Width="100px">Zip Code:</asp:Label>
      <asp:TextBox id="txtZip" runat="server" Width="184px"></asp:TextBox>&nbsp; 
      (required: any five&nbsp;digits)<br />
      <br />
      
      <asp:Label id="Label8" runat="server" Width="93px" Height="19px">Contract:</asp:Label>&nbsp;
      <asp:CheckBox id="chkContract" runat="server"></asp:CheckBox><br />
      <br />
      
      <asp:Label id="lblResults" runat="server" Width="575px" Height="121px" Font-Bold="True"></asp:Label>
    </div>
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Web.Configuration;
using System.Data.SqlClient;

public partial class AuthorManager : System.Web.UI.Page
{
    private string connectionString = WebConfigurationManager.ConnectionStrings["Pubs"].ConnectionString;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            FillAuthorList();
        }
    }

    private void FillAuthorList()
    {
        lstAuthor.Items.Clear();
        string selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                ListItem newItem = new ListItem();
                newItem.Text = reader["au_lname"", " + reader["au_fname"];
                newItem.Value = reader["au_id"].ToString();
                lstAuthor.Items.Add(newItem);
            }
            reader.Close();
        }
        catch (Exception err)
        {
            lblResults.Text = "Error reading list of names. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }
    }

    protected void lstAuthor_SelectedIndexChanged(object sender, EventArgs e)
    {
        string selectSQL;
        selectSQL = "SELECT * FROM Authors ";
        selectSQL += "WHERE au_id='" + lstAuthor.SelectedItem.Value + "'";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;

        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            reader.Read();

            txtID.Text = reader["au_id"].ToString();
            txtFirstName.Text = reader["au_fname"].ToString();
            txtLastName.Text = reader["au_lname"].ToString();
            txtPhone.Text = reader["phone"].ToString();
            txtAddress.Text = reader["address"].ToString();
            txtCity.Text = reader["city"].ToString();
            txtState.Text = reader["state"].ToString();
            txtZip.Text = reader["zip"].ToString();
            chkContract.Checked = (bool)reader["contract"];
            reader.Close();
            lblResults.Text = "";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error getting author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

    }
    protected void cmdNew_Click(object sender, EventArgs e)
    {
        txtID.Text = "";
        txtFirstName.Text = "";
        txtLastName.Text = "";
        txtPhone.Text = "";
        txtAddress.Text = "";
        txtCity.Text = "";
        txtState.Text = "";
        txtZip.Text = "";
        chkContract.Checked = false;
        
        lblResults.Text = "Click Insert New to add the completed record.";


    }
    protected void cmdInsert_Click(object sender, EventArgs e)
    {
        if (txtID.Text == "" || txtFirstName.Text == "" || txtLastName.Text == "")
        {
            lblResults.Text = "Records require an ID, first name, and last name.";
            return;
        }
        string insertSQL;
        insertSQL = "INSERT INTO Authors (";
        insertSQL += "au_id, au_fname, au_lname, ";
        insertSQL += "phone, address, city, state, zip, contract) ";
        insertSQL += "VALUES (";
        insertSQL += "@au_id, @au_fname, @au_lname, ";
        insertSQL += "@phone, @address, @city, @state, @zip, @contract)";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(insertSQL, con);

        cmd.Parameters.AddWithValue("@au_id", txtID.Text);
        cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text);
        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@city", txtCity.Text);
        cmd.Parameters.AddWithValue("@state", txtState.Text);
        cmd.Parameters.AddWithValue("@zip", txtZip.Text);
        cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));

        int added = 0;
        try
        {
            con.Open();
            added = cmd.ExecuteNonQuery();
            lblResults.Text = added.ToString() " record inserted.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error inserting record. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

        if (added > 0)
        {
            FillAuthorList();
        }
    }

    protected void cmdUpdate_Click(object sender, EventArgs e)
    {
        string updateSQL;
        updateSQL = "UPDATE Authors SET ";
        updateSQL += "au_fname=@au_fname, au_lname=@au_lname, ";
        updateSQL += "phone=@phone, address=@address, city=@city, state=@state, ";
        updateSQL += "zip=@zip, contract=@contract ";
        updateSQL += "WHERE au_id=@au_id_original";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(updateSQL, con);

        cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
        cmd.Parameters.AddWithValue("@au_Lname", txtLastName.Text);
        cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
        cmd.Parameters.AddWithValue("@address", txtAddress.Text);
        cmd.Parameters.AddWithValue("@city", txtCity.Text);
        cmd.Parameters.AddWithValue("@state", txtState.Text);
        cmd.Parameters.AddWithValue("@zip", txtZip.Text);
        cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
        cmd.Parameters.AddWithValue("@au_id_original", lstAuthor.SelectedItem.Value);

        int updated = 0;
        try
        {
            con.Open();
            updated = cmd.ExecuteNonQuery();
            lblResults.Text = updated.ToString() " record updated.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error updating author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }

        if (updated > 0)
        {
            FillAuthorList();
        }

    }
    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        string deleteSQL;
        deleteSQL = "DELETE FROM Authors ";
        deleteSQL += "WHERE au_id=@au_id";

        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(deleteSQL, con);
        cmd.Parameters.AddWithValue("@au_id ", lstAuthor.SelectedItem.Value);

        int deleted = 0;
        try
        {
            con.Open();
            deleted = cmd.ExecuteNonQuery();
            lblResults.Text = "Record deleted.";
        }
        catch (Exception err)
        {
            lblResults.Text = "Error deleting author. ";
            lblResults.Text += err.Message;
        }
        finally
        {
            con.Close();
        }
        if (deleted > 0)
        {
            FillAuthorList();
        }
    }
}


File: Web.config

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="Pubs" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Pubs;Integrated Security=SSPI"/>
  </connectionStrings>
</configuration>
18. 42. SqlServer
18. 42. 1. Connect to SQL server with integrated Authentication or SQL Authentication
18. 42. 2. Execute delete command with SqlCommand against SqlServer
18. 42. 3. You can connect to a Local database named MyLocalData.mdf by using the following connection string:
18. 42. 4. For example, the following connection string enables you to connect to a Server database named MyData:
18. 42. 5. You use SQLCMD by opening a command prompt and connecting to your database with the following command:
18. 42. 6. Read data from SQL server and fill asp:dropdownlist (C#)
18. 42. 7. Handle table relationship (C#)
18. 42. 8. Insert, update and delete (C#)
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.