This tutorial will show you how to use C# and AJAX to create a Data Access Component that will display data from a SQL database and also allow edits of the data.
Using Visual Studio.NET to manage and manipulate data can save us a lot of time. VS.NET ships with built-in tools making it extremely easy for us to work with data sources. However, it also allows us to create our own Data Access Components, allowing us more control.
In this tutorial you will learn how to create a Data Access Component (DAC) and how we can write a method that will allow us to update the records within the database using a FormView control. Instead of using the built-in Update function, we will be writing our own to demonstrate the control we have.
Before we do anything else, we need a database. In this example, we will be working with a SQL database with one table, which has three columns - id, name and age. Once we have set up our database, we will add some sample records to work with. If you already have a database you wish to work with, then great.
The first thing we want to do is to create our class. This will handle all the interaction with our database - reading and writing. We will need to write a method for reading the data, and then a method for updating records. We will start off with reading the database:
private static readonly string _connectionString;
private int _id; private string _name; private string _age;
public int Id {
get {
return _id; } set {
_id = value; } }
public string Name {
get {
return _name; } set {
_name = value; } }
public string Age {
get {
return _age; } set {
_age = value; } }
public List<People> GetAll() {
List<People> results = new List<People>(); SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("SELECT id,name,age FROM tblPeople", con); using (con) {
con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) {
People newPerson = new People(); newPerson.Id = (int)dr["Id"]; newPerson.Name = (string)dr["Name"]; newPerson.Age = (string)dr["Age"]; results.Add(newPerson); } } return results; }
static People() {
_connectionString = WebConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; } |
Server Intellect offers Windows Hosting Dedicated Servers at affordable prices. I'm very pleased!
At present, the above code is just for retrieving the data from the database. We use a List collection to gather all records from the database, and then return to the object that calls the method. In this case, we will use the ObjectDataSource to call the method, but that's a little later in the ASPX code. Because we want to add the functionality of adding data to the database, we will need to add another method, which will look something like this:
public void Update(int id, string name, string age) {
SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("UPDATE tblPeople SET name=@name,age=@age WHERE id=@id", con); cmd.Parameters.AddWithValue("@id", id); cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@age", age); using (con) {
con.Open(); cmd.ExecuteNonQuery(); } } |
If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!
This method uses SQL statements to update the database record with variables to it from whatever calls it. In this example, the ObjectDataSource will be calling it, which we will get to a little later.
So the entire code-behind for the class looks something like this:
using System; using System.Data; using System.Web.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Collections; using System.Collections.Generic; using System.Data.SqlClient;
/// <summary> /// Summary description for People /// </summary> public class People {
private static readonly string _connectionString; private int _id; private string _name; private string _age; public int Id {
get {
return _id; } set {
_id = value; } } public string Name {
get {
return _name; } set {
_name = value; } } public string Age {
get {
return _age; } set {
_age = value; } } public void Update(int id, string name, string age) {
SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("UPDATE tblPeople SET name=@name,age=@age WHERE id=@id", con); cmd.Parameters.AddWithValue("@id", id); cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@age", age); using (con) {
con.Open(); cmd.ExecuteNonQuery(); } } public List<People> GetAll() {
List<People> results = new List<People>(); SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("SELECT id,name,age FROM tblPeople", con); using (con) {
con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) {
People newPerson = new People(); newPerson.Id = (int)dr["Id"]; newPerson.Name = (string)dr["Name"]; newPerson.Age = (string)dr["Age"]; results.Add(newPerson); } } return results; } static People() {
_connectionString = WebConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; } } |
We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we've ever dealt with!
Now we are done writing the class, we need to implement it into the ASPX page.
To do this, all we will do is include two controls: GridView and ObjectDataSource. We reference the Class name we just created with the TypeName of the data source and then we reference the methods: GetAll method is used to select data, and Update method is used to update data. The ASPX page will look something like this:
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1"
DataKeyNames="id" AutoGenerateEditButton="true" Width="370px" /> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="People"
SelectMethod="GetAll" UpdateMethod="Update" /> </form> |
We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!
We can further improve this by adding a little AJAX to make the editing process a lot smoother. By adding a ScriptManager and UpdatePanel, we are forcing just the form to reload instead of the whole page:
<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" AutoGenerateEditButton="true" Width="370px" /> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" TypeName="People"
SelectMethod="GetAll" UpdateMethod="Update" /> </ContentTemplate> </asp:UpdatePanel> </form> |
Looking for the Visual Studio.NET 2008 VB.NET version? Click here!
Looking for more .NET Tutorials? Click Here!