Academic Students Projects | Software School Projects | Free Source Codes | College
Projects By LANGUAGE
Libraries
Articles & seminars
Source Code
Building a Custom 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: 
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>
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 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()
Download project code