Creating Custom Objects in ASP.NET 4.0 with C#
In this tutorial, we will be creating our own class that will represent a Person object, which we will store in a database. Within this class, we will create custom properties and methods to interact with that object. We will also show you how to use a collection class to group together these objects and handle them with ease.
To get started, we will create a new web application in Visual Studio. We will be working primarily with the Default.aspx page and a .cs file. So let us begin by adding the Class. Right-click the App_Code folder in the Solution Explorer (if you do not see it, right-click your solution and choose Add ASP.NET Folder > App_Code), and then choose Add New Item… We want to add a new Class; name it People.cs and click Ok. We should get something like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for People
/// </summary>
public class People
{
public People()
{
//
// TODO: Add constructor logic here
//
}
}
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
First, let’s wrap the Class in a namespace. This makes it easier for us to keep our code together, especially when building bigger applications and grouping multiple classes in one namespace. Then rename the Class to Person – People will be the wrapper namespace; Person will be the class.
namespace ProgrammingHelp.People
{
public class Person
{
}
}
We can wrap our Properties in a #region. We will need to specify all properties of our object, and set the default values and data types. We do this as follows:
#region properties
/// <summary>
/// Gets or sets PersonID. [Default value is 0].
/// </summary>
public Int32 PersonID
{
get
{
return _PersonID;
}
set
{
_PersonID = value;
}
}
private Int32 _PersonID = 0;
/// <summary>
/// Gets or sets the First Name of the Person. [Default value is ''].
/// </summary>
public String FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
private String _FirstName = "";
/// <summary>
/// Gets or sets the Last Name of the Person. [Default value is ''].
/// </summary>
public String LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
private String _LastName = "";
/// <summary>
/// Gets or sets the City of the Person. [Default value is ''].
/// </summary>
public String City
{
get
{
return _City;
}
set
{
_City = value;
}
}
private String _City = "";
/// <summary>
/// Gets or sets DateTime the Person was added. [Default value is the current Date/Time].
/// </summary>
public DateTime DateTimeAdded
{
get
{
return _DateTimeAdded;
}
set
{
_DateTimeAdded = value;
}
}
private DateTime _DateTimeAdded = DateTime.Now;
/// <summary>
/// Gets or sets the Age of the Person. [Default value is 0].
/// </summary>
public int Age
{
get
{
return _Age;
}
set
{
_Age = value;
}
}
private int _Age = 0;
#endregion
private void SetObjectData(SqlDataReader theObjReader)
{
this._PersonID = Convert.ToInt32(theObjReader["PersonID"]);
this._FirstName = theObjReader["FirstName"].ToString();
this._LastName = theObjReader["LastName"].ToString();
this._City = theObjReader["City"].ToString();
this._Age = Convert.ToInt16(theObjReader["Age"]);
this._DateTimeAdded = Convert.ToDateTime(theObjReader ["DateTimeAdded"]);
}
I just signed up at Server Intellect and couldn’t be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.
We place all the Class’s methods below the Properties, and can use another #region to group them together. The SetObject method takes a parameter of a SqlDataReader, which is then used to set the properties of the object, using the correct data types as specified in the Properties. Now we can call this method using a constructor like so:public Person(SqlDataReader theObjReader)
{
SetObjectData(theObjReader);
}
This constructor will be used to build an object from a SqlDataReader. When this constructor is called, a SqlDataReader must be passed, and a Person object will be returned. However, we’re not always going to be able to use a SqlDataReader to build an object from. This constructor will be mainly used for internal methods, when retrieving records from the database and returning an object, for example:
A more common constructor to use would be one that takes the parameter of the object ID. This way, we can take that ID, pull the corresponding record from the database and then return the object. To do this, let’s add our database. Right-click the App_Data folder in Solution Explorer, then choose to Add New Item.. SQL Server Database. Give it a name and hit OK. Once opened, we want to create a new table People. We can do this straight in the Visual Studio environment using Server Explorer:

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
We will create the same columns as our Class Properties, with similar types – PersonID will be bigint; FirstName varchar(50); Age smallint, and DateTimeAdded datetime for example. Once saved, you can right-click the table and choose to Show Table Data. This will allow you to enter some sample data to test with. Add a test record or two.In this example, we are going to illustrate how to use a custom class to make use of collections of data. Going back to our class, we will make a collection class of the existing Person class, which we can call People. To do this, we need to create a new class outside of the Person class, but within the namespace, and we need to inherit from the CollectionBase class. First thing to do is to make sure we have the following reference at the top of our code and declare the class like so:
using System.Collections;//And the class we will be declaring[Serializable]
public class People : CollectionBase
{
}
[Serializable]
public class People : CollectionBase
{
public int TotalRecords
{
get
{
return _TotalRecords;
}
set
{
_TotalRecords = value;
}
}
protected int _TotalRecords = 0;
public int Add(Person thePerson)
{
this.TotalRecords++;
return List.Add(thePerson);
}
public void Insert(Int32 index, Person thePerson)
{
List.Insert(index, thePerson);
}
public void Remove(Person thePerson)
{
List.Remove(thePerson);
}
public bool Contains(Person thePerson)
{
return List.Contains(thePerson);
}
public int IndexOf(Person thePerson)
{
return List.IndexOf(thePerson);
}
public void CopyTo(Person[] array, int index)
{
List.CopyTo(array, index);
}
public Person this[int index]
{
get
{
return (Person)List[index];
}
set
{
List[index] = value;
}
}
}
public static People GetAllPeople()
{
People PeopleCollection = new People();
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
try
{
SqlCommand cmd = new SqlCommand("sp_GetAllPeople", connection);
cmd.CommandType = CommandType.StoredProcedure;
connection.Open();
SqlDataReader objReader = cmd.ExecuteReader();
while (objReader.Read())
{
Person newPerson = new Person(objReader);
PeopleCollection.Add(newPerson);
}
objReader.Close();
connection.Close();
}
catch
{
connection.Close();
}
return PeopleCollection;
}
Need help with cloud hosting? Try Server Intellect. We used them for our cloud hosting services and we are very happy with the results!
Notice that although they are two separate classes, we have full access to the People collection from the Person class. This is because they both reside in the same namespace. So we start by declaring an empty People collection, then define our connection string. Next, we use a try..catch to attempt to execute the Stored Procedure to retrieve all records from the database. Our Stored Procedure looks something like this:ALTER PROCEDURE dbo.sp_GetAllPeople
AS
SELECT * FROM People
<asp:Repeater ID="repeater_People" runat="server">
<HeaderTemplate>
<table width="600">
<tr>
<th width="100">ID</th><th width="150">Name</th>
<th width="100">City</th><th width="100">Age</th> <th width="150">Added</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("PersonID") %></td>
<td><%# Eval("FirstName") %> <%# Eval("LastName") %></td>
<td><%# Eval("City") %></td>
<td><%# Eval("Age") %></td>
<td><%# Eval("DateTimeAdded") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
using ProgrammingHelp.People;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
SetDropDown();
}
}
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
Now if you run the page, the repeater should display the contents of your database table. This may seem like the long way around getting a few items to display in a repeater, and it is. Custom Objects, however, are extremely useful when using larger amounts of data across multiple pages.Success!
Congratulations! We have learned how to create Custom Classes and Objects, as well as a Collection Class that can be assigned to a Repeater to display a collection of custom objects. Have a good one!
CreatingCustomObjects
