Creating Custom Objects in ASP.NET 3.5 and C#

Category: ASP.NET

Using Custom Objects and Collection Class for Binding Data - in C#

Introduction

This article will walk you through creating a custom object and collection class for that object, which will allow you to gain access to the custom properties and methods in the code-behind. Using objects makes it so much easier to manage larger web applications, as we can associate data with more precision and ease. This article is written for users of Visual Studio.NET 2008, but 2005 users can still benefit.

In this article, 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 the object. We will also show you how to use a collection class to group together these objects and handle them with ease.

What we will learn in this article:

  • How to create a custom object;
  • How to create a collection class for that object that will allow us to group objects together and assign to a data source.

Getting Started
To get started, we will start 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 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 description for People
///

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
{

}
}

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

public Int32 PersonID
{
get
{
return _PersonID;
}
set
{
_PersonID = value;
}
}
private Int32 _PersonID = 0;

public String FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
private String _FirstName = "";

public String LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
private String _LastName = "";

public String City
{
get
{
return _City;
}
set
{
_City = value;
}
}
private String _City = "";

public DateTime DateTimeAdded
{
get
{
return _DateTimeAdded;
}
set
{
_DateTimeAdded = value;
}
}
private DateTime _DateTimeAdded = DateTime.Now;

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

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 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 will 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 file:

using System.Collections;

Next, declare the class like so:

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

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!

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 (which was inserted into the Web.config, for more information on connection strings, see ConnectionStrings.com). 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;









ID Name City Age Added

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:

using ProgrammingHelp.People;

Then we can reference the method to get all People, and assign to the repeater:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
}
}

protected void BindRepeater()
{
repeater_People.DataSource = Person.GetAllPeople();
repeater_People.DataBind();
}

Now if you run the page, the repeater should display the contents of your database table. This may seem like a long way around getting a few items to display in a repeater, and it is. Custom Object, however, are extremely usefull when using larger amounts of data across multiple pages.

What we have Learned

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.



Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!