ASP.NET
  Home arrow ASP.NET arrow Updating and Inserting Data with ADO.NET a...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET

Updating and Inserting Data with ADO.NET and ASP.NET 2.0
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2007-09-24

    Table of Contents:
  • Updating and Inserting Data with ADO.NET and ASP.NET 2.0
  • Closing SqlConnection and SqlDataReader objects through the using block
  • Inserting and Updating Data using the SqlCommand
  • Using Parameterized Queries to Retrieve Data

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Updating and Inserting Data with ADO.NET and ASP.NET 2.0


    (Page 1 of 4 )

    In this article we will use methods of the SqlCommand class to insert and update data. We will look at a technique for making sure that the Close() method of the SqlConnection and the SqlDataReader classes is called even when an exception is raised.

    I like to introduce concepts as well as code in the same article. In the previous article, we used the SqlConnection, SqlCommand and the SqlDataReader classes to retrieve data from Northwind's Employees table, but we didn't investigate those objects. We can't talk about a big part of the ADO.NET technology in one article, so in the next example I'm going to create the example we have used in the previous article but modify the code so we can talk more about the SqlConnection and the SqlCommand classes.

    So let's see the code first, then discuss it. Create a new website and add a ListBox and a Label control to the page as in the following code:

    <%@ 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:ListBox ID="ListBox1" runat="server" Height="165px"
    Width="152px"></asp:ListBox>
          <asp:Label ID="Label1" runat="server"
    ForeColor="Red"></asp:Label>
        </div>
      </form>
    </body>
    </html>

    Now replace the auto-generated class template code in the Default.aspx.cs class with the following:

    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;

    // use the namespace of the ADO.NET SQL Server Data Provider
    using System.Data.SqlClient;

    public partial class _Default : System.Web.UI.Page{
      protected void Page_Load(object sender, EventArgs e){
        // create the connection and set the connection string
        // through the connection object's constructor
        string connectionString = "Data Source=(local);
        Initial Catalog=Northwind;Integrated Security=True";
        SqlConnection connection = new SqlConnection
    (connectionString);

        // create the command object and the T-SQL SELECT statement
        // and assign the connection object along with the T-SQL
        // SELECT statement to command object through the
        // constructor
        string commandText = "SELECT LastName, FirstName FROM
    Employees";
        SqlCommand command = new SqlCommand(commandText, connection);

        // we have initialized the connection and the command so 
        // it's time to open the connection and execute the command
        // using a try/catch block to handle exceptions
        SqlDataReader dataReader;
        try{
          // check if the connection is already open
          if (connection.State == ConnectionState.Closed){
            connection.Open();
          }
          // get a SqlDataReader object from the Command's 
          // ExecuteReader() method
          dataReader = command.ExecuteReader();

          // adding the returned rows to the listbox control
          while (dataReader.Read()){
            ListBox1.Items.Add(dataReader["LastName"] + ", " +
    dataReader["FirstName"]);
          }
        }
        catch (Exception ex){
          Label1.Text = ex.Message;
        }
        finally{
          connection.Close();
        }
      }
    }

    When you run the page you will get the same results as you did with the previous article's example.

    In the previous article we assigned the connection string to the SqlConnection object through the property SqlConnection.ConnectionString. Today, however, we passed the connection string to the SqlConnection object's constructor, so we wrote less code. Also we passed the T-SQL SELECT statement along with the SqlConnection object to the SqlCommand object's constructor. So instead of assigning the SqlConnection object to the SqlCommand.Connection property we  passed the SqlConnection object to the SqlCommand's constructor, which has the same effect (both techniques associate the SqlConnection with the SqlCommand object).

    Now we are ready to open the connection. We used the SqlConnection.State property to test whether the connection is already open. The SqlConnection.State property takes its values from the ConnectionState enumeration. Only two values are used for this ADO.NET release: the Closed and the Open values. We used the SqlConnection.State property because if we call the SqlConnection.Open() method on an opened connection we would get an exception. We opened the connection, through calling the SqlConnection.Open() method, only if the SqlConnection.State property's value equals ConnectionState.Closed.

    If the connection is already open we simply execute the T-SQL SELECT statement and return our SqlDataReader object. Note that if an exception has been generated the catch block gets executed and the exception is passed to it as a parameter. The exception message will be displayed in the label control's text, and then the connection is closed in the finally block. Let's do one more thing before we move on to inserting and updating data.

    More ASP.NET Articles
    More By Michael Youssef


       · Before reading this article, please read the article Introducing ADO.NET with...
     

    ASP.NET ARTICLES

    - Adding Content to a Static ASP.NET Website
    - Building a Static ASP.NET Website in a Basic...
    - Develop Your First ASP.NET Website with Visu...
    - Run ASP.NET in Windows XP Home with Cassini ...
    - How to Test a Web Application
    - How to Add Code and Validation Controls to a...
    - Working in Source and Split Views to Build a...
    - How to Build a Web Form for a One-Page Web A...
    - How to Develop a One-Page Web Application
    - An ASP.NET Web Application in Action
    - Developing ASP.NET Web Applications
    - An Introduction to ASP.NET Web Programming
    - Introduction to the ADO.NET Entity Framework...
    - Completing an In-Text Advertising System und...
    - Programming an In-Text Advertising System un...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek