This tutorial will show you how to create your own Data Access Component and also how to display the time it takes to retrieve data from a SQL database. C# version.

Using Visual Studio.NET 2008, we can build our own Data Access Components to work with and manipulate data. In this tutorial, we will look at how we can do this, and how we can also retrieve the duration of data retrieval, which can be useful when dealing with large amounts of data. For this example, we will be working with a SQL database, and we will be creating our own class to retrieve the data. We will be using the Object Data Source to interact with our class, and a GridView to display the data.

The database we will be working with will have just one table, and three columns – id, name and age. Once created, we will add some sample data to use.

When our database is ready to go, we can start building our class that will retrieve data from our database. The class will have a method to retrieve all records from the database and input into a List. Our class will look something like this:

We create a ‘GetAll’ method that uses a List to collect all data from the database. Then, using a loop, we add each record from the database into the results List we created. This is the List that is then returned. We will use this method to select data, using the ObjectDataSource. We can now build our ASPX page like so:

Notice that we have assigned the GetAll method to our SelectMethod attribute of our ObjectDataSource, and the TypeName is the name of the Class. We also have a method that fires on the OnSelected event. This means that when the ObjectDataSource selects data (through the class), the following code is processed:

This is where we output the time it took to retrieve the data.
The entire code-behind will look something like this:

The entire code of the class is follows:

Download Source Files