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
//
}
}


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
    {
 
    }
}


The next thing to do will be to create the default constructor for the Class and set the Properties. The default constructor (public Person()) will instantiate an empty Person object, when called. It will look like this:

public 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

Notice we make the Properties public so that we can reference them outside of the class, and we set the defaults within the class, using Private. We also want to create a constructor that will instantiate a usable object. We can create many constructors that take various overloads. Let us start with the first, which will be used to build the object using a SqlDataReader. First, we will create a method that the constructor will use to parse the DataReader and set the object with the values:

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"]);
        }

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 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
{
}

Now, similar to our Properties of the Person class, we will add Properties and Methods of the collection class:

[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;
        }
    }
}

Because we are inheriting from the CollectionBase class, a lot of the functionality is already there – we are simply customizing it for our Person class. Now to demonstrate how this works, we will create a method in our Person Class that will get all records (People) from the database, and return them in a People collection. So the method will look something like this:

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;
}

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

Once the Stored Procedure is executed, we check to see if any records are returned, and if so, we call the Person constructor to set the new object with the SqlDataReader, and then add it to the new collection. Finally, once all records have been processed, we close the connection and the method will return the People collection it just built. The great thing about collections, is that we can assign them to the DataSource of ASP.NET Controls and their Properties can be used directly. For example, we will use this method to assign the collection to a Repeater’s DataSource, then display the Properties on the page. To do this, move to the Default.aspx page and add a Repeater control like so:

<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>

Notice we are using the Property names to display to the page. We can assign the collection on page load, but first, we must remember to add the reference to the namespace then we can reference the method to get all People, and assign it to the repeater.

using ProgrammingHelp.People;
 
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
            SetDropDown();
        }
    }

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!