This tutorial will show you how to create your own class in ASP.NET and C#.In this tutorial, we will look at how to create a Custom
Class that will represent an object.
Building a Custom Class in ASP.NET and C#
This tutorial will show you how to create your own class in ASP.NET and C#
In this tutorial, we will look at how to create a Custom
Class that will represent an object. When working with databases in Web
Applications, it is often useful to have an object representing that
data, rather than using the built-in types such as a DataTable. By
creating your own class, you can gain access to the Properties instead
of referencing row and column numbers. An example would be if you're
working with data from a database that consisted of a group of people.
The columns could be name, age, and telephone. If you used a datatable
to retrieve and interact with this data, it could get messy very
quickly. But if you created a class to represent the data, then you
would be able to programmatically reference the properties (name, age,
and telephone) directly.
In this example, we will use a SQL Database and create a class to
represent the data. We will keep it simple and use the following
columns in the table: ID, Name, Age, Telephone.
Let's begin by starting a new Web Application in Visual Studio.
Right-click on the App_Data folder in Solution Explorer, and choose Add
New Item.. SQL Server Database. Once it opens up in the Server Explorer
window, right-click the Tables folder and choose to Add New Table. Add
the following columns and data types:
ID bigint
Name varchar(50)
Age smallint
Telephone varchar(20)
We also want to make the ID column the Primary Key, and in the
properties, set Identity Specification to Yes. Then Save the table, and
add the Connection String to the Web.config:
If you're unsure about the Connection String, see ConnectionStrings.com
Now let us begin writing our Class. If you don't have an App_Code
folder in your Solution Explorer, right-click your Project and choose
to Add ASP.NET Folder > App_Code. Then right-click the App_Code
folder and choose to Add New Item.. Class. Give it a name. You should
then be presented with something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
///
/// Summary description for Person
///
public class Person
{
public Person()
{
//
// TODO: Add constructor logic here
//
}
}
|
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!
The first thing we should do is to add the Properties. We want the
Properties to refelect the columns of the table in the database. We
will need to set the data types as well:
#region properties
public Int32 ID
{
get
{
return _ID;
}
set
{
_ID = value;
}
}
private Int32 _ID = 0;
public String Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}
private String _Name = "";
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
private int _Age = 0;
public String Telephone
{
get
{
return _Telephone;
}
set
{
_Telephone = value;
}
}
private String _Telephone = "";
#endregion
|
Notice that each Property is public so that we can access it from
outside the class. We also set the default values for each Property.
Now that we've got all of our Properties, we can move onto the
constructors and methods. Let's start with the base method -
SetObjectData. We will use this method to build our object from a
SqlDataReader, but before we do, we need to add the following reference:
|
using System.Data.SqlClient;
|
I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.
The reference to this class will allow us to interact with our SQL
Server Database. Our SetObjectData method will take the parameter of a
SqlDataReader and then use that to fill the properties we have just
created:
private void SetObjectData(SqlDataReader theObjReader)
{
try
{
this._ID = Convert.ToInt32(theObjReader["ID"]);
this._Name = theObjReader["Name"].ToString();
this._Age = Convert.ToInt16(theObjReader["Age"]);
this._Telephone = theObjReader["Telephone"].ToString();
}
catch
{ }
}
|
We make this method private because we don't want it to be
accessible beyond the class; only class methods should call it. From
within the method, when 'this.' is typed, you should be presented with
the intellisense dropdown, which holds the properties we added earlier.
We will set these properties using the passed SqlDataReader.
Now we can create a constructor that will use this method. By doing
this, we protect the method from external usage, but allow it to still
be used with the constructor. This will allow us to create a new object
just by passing a valid SqlDataReader. By valid, we mean that it must
still hold the correct properties in order for the object to be built
and returned. The constructor will look something like this:
public Person(SqlDataReader theObjReader)
{
SetObjectData(theObjReader);
}
|
Another constructor we can create that is always useful is one that
will retrieve an object based upon the ID passed to it. This allows us
to populate an object with the record we want, just by specifying its
ID. For this method, we will need to reference the following namespaces:
using System.Data;
using System.Web.Configuration;
|
The method will look something like this:
public Person(Int32 thePersonID)
{
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd;
cmd = new SqlCommand("sp_GetPersonByID", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ID", thePersonID);
connection.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
SetObjectData(objReader);
}
objReader.Close();
connection.Close();
}
catch
{
connection.Close();
}
}
|
We are taking a parameter of type Int32 and then simply executing a
Stored Procedure that will compare this ID and return the match. With
that match we use our SetObjectData method to build the Person object.
To create a Stored Procedure, open up the Server Explorer window and
right click on the Stored Procedures folder, choose Add New. Our Stored
Procedure looks like this:
CREATE PROCEDURE dbo.sp_GetPersonByID
@ID bigint
AS
SELECT * FROM Table1 WHERE ID=@ID
|
Our class is pretty much done for the most part, but many public
methods can be added for use with and relating to the custom object.
For example, we can create a public method that can be called from any
ASPX page that will insert new data into the database, using the
object. To do this, we will create a public method that will return an
integer, which will be the ID of the new record just inserted. If
insert fails, the method will return zero. Because we are passing an
object to the method, we will set the parameters like so:
public static Int32 InsertPerson(Person thePerson)
{
Int32 newPersonID = 0;
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("sp_InsertPerson", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name", thePerson.Name);
cmd.Parameters.AddWithValue("@Age", thePerson.Age);
cmd.Parameters.AddWithValue("@Telephone", thePerson.Telephone);
connection.Open();
newPersonID = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();
}
catch
{
connection.Close();
}
return newPersonID;
}
|
We use a similar structure to the constructor with the Int32
parameter, but we do not need to use the SetObjectData method on this
one, as we are not returning the object. We are taking the object as a
parameter, adding that data to the database, then returning its ID. All
the object's public properties can be accessed using the instance name
and then a period(.), just like other objects.
Our Insert Stored Procedure looks like this:
CREATE PROCEDURE dbo.sp_InsertPerson
@Name varchar(50),
@Age smallint,
@Telephone varchar(20)
AS
INSERT INTO Table1
([Name], Age, Telephone)
VALUES (@Name, @Age, @Telephone)
SELECT SCOPE_IDENTITY()
|
|