In this tutorial, we will be looking at the Command Object and creating our own Data Access Component using the Object Data Source control. We will be using a SQL database, and then creating a class to represent our database. We will use this class (DAC) to interact with an Object Data Source.

Getting Started

The very first thing we need to do is to create our database. We will be using a SQL database, so open up Visual Studio and create a new web project in C#. Right-click the project in Solution Explorer and choose Add New Item.. SQL Server Database. If you are asked to place in the App_Data folder, choose Yes.


We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!

Once the database has been added to the project, we can then goto Server Explorer and right-click on the Tables folder for the new database and choose to Add New Table. We should then be presented with the table designer. For this example, we will have two columns: ID (int) and Name(varchar(50)). We also want to make sure that ID is the Primary Key and also set Identity Specification to Yes. Then we can save the table, name it tblNames.

Now we will add some data to the database by right-clicking the table in Server Explorer and choosing Show Table Data. Notice we are required to only enter a name as the ID will be auto-generated for each record.

Next, we want to add a class to our project, where we will build the methods used for manipulating our data. Right-click the project in Solution Explorer, and then choose Add ASP.NET Folder > App_Code. An App_Code folder should be added to the project, which we will now right-click and choose Add New Item.. Class, and name it Names. We should be presented with the default code for the new class:
Code Block
Names.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


/// Summary description for Names

public class Names
{
    public Names()
    {
    //
    // TODO: Add constructor logic here
    //
    }
}

If you’re ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.

We need a connection string to work within this class, so we will add just before the system.web in our Web.config:

Code Block
Web.config
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Now we can save Web.config and go back to the class. The first thing we need to do is define the variable we will be using – one for the connection string, and one for each column we will be working with in the database. Then we create a get and set for each column, also, and finally assign our connection string. In order to use the WebConfigurationManager to retrieve our Connection String from the Web.config, we need to add the System.Web.Configuration assembly reference, which is not usually added by default.

Now this is the base upon which we can build our class. From here we will add methods to both retrieve data and then also delete data from the database. Our basis looks like this:
Code Block
Names.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;

/// <summary>
/// Summary description for Names
/// </summary>
public class Names
{
    private static readonly string _connectionString;

private int _id;
private string _name;

    public int ID
{
get
{
return _id;
}
set
{
_id = value;
}
}

public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
For the retrieval method, we will be using a SqlCommand and a List<> collection, for which we will need to add the System.Data.SqlClient and System.Collections.Generic assembly references. We will use the List<> collection with the class we created as our object, then we use SQL to loop through the data and add each record to the collection.
Code Block
Names.cs
public List<Names> GetData()
{
List<Names> results = new List<Names>();
SqlConnection con = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("SELECT ID,Name FROM tblNames" con);
using (con)
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Names theName = new Names();
theName.ID = System.Convert.ToInt32((int)(dr["ID"]));
theName.Name = System.Convert.ToString(dr["Name"]);
results.Add(theName);
}
}
return results;
}
Notice that when we reference the Names variable (theName), we can access the properties of the class (ID, Name), which are even shown in the IntelliSense. This makes it very easy for us to work with custom classes:

The method we are going to create to enable us to delete records from the database will be significantly easier to code than the one we just created. We are going to simply use a SQL statement to delete the record that we are given the ID to, and then apply that query to the database to save changes.
Code Block
Names.cs
public void Delete(int id)
    {
SqlConnection con = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand("DELETE tblNames WHERE ID=@Id" con);
cmd.Parameters.AddWithValue("@Id", id);
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Again we are using SqlCommand to apply a regular SQL statement against the database to delete a record matching the ID that has been passed to the method. Similar to this, we can also add a third method to update the database data.
Code Block
Names.cs
public void Update(int id, string name)
    {
        SqlConnection con = new SqlConnection(_connectionString);
        SqlCommand cmd = new SqlCommand("UPDATE tblNames SET Name=@name  WHERE ID=@id", con);
        cmd.Parameters.AddWithValue("@id", id);
        cmd.Parameters.AddWithValue("@name", name);
        using (con)
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
The last thing we need to do is to incorporate the class into our ASPX page, and make use of it. To do this, we will be using the GridView control and the ObjectDataSource, which will use the class we just created. We use the Object Data Source attributes to specify the methods to use for Selecting, Deleting, and Updating of database data, and TypeName refers to the class we created. Because we are using in Visual Studio.NET 2008, also, we can easily add AJAX functionality by including a ScriptManager and an UpdatePanel.
Code Block
Default.aspx
<form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:GridView ID="GridView1" runat="server" DataSourceID= "ObjectDataSource1" DataKeyNames="ID" AutoGenerateDeleteBut ton="true" Width="350px" AutoGenerateEditButton="true" />  
            <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"  TypeName="Names" SelectMethod="GetData" DeleteMethod=" Delete" UpdateMethod="Update" />
        </ContentTemplate>
        </asp:UpdatePanel>
    </form>

We used over 10 web hosting companies before we found Server Intellect. Our new server with cloud hosting,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect’s customer support and assistance are the best we’ve ever experienced.


Success!

Congratulations! We have learned how to create our own Data Access Component to connect, retrieve and delete data from a SQL Server Database. Download the source file below for a more in depth look at the Data Access Component, have a good one!

DataAccessComponent