This tutorial will demonstrate how to use one simple SQL command to increment a value within a database using ASP.NET 4.0 and C#.

Adding a Database

To demonstrate how to increment a value using a simple SQL command, we will need a simple web site with a database. At this point I have created a new ASP.NET Empty Web Site. Next, we need to add a database with a small table in it. To do this:

  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder in your solution explorer.
  5. Select add new item…
  6. Select a Sql Server Database.
  7. Click add.
  8. Expand the Database.mdf folder.
  9. Right click the Tables folder.
  10. Select add new table.
  11. Add the following columns with their respective types to the table:
    Column Name Data Type
    ID int
    Number int
  12. Right click the ID column and select Set Primary Key.
  13. Check the IsIdentity property of the ID column to true.
  14. Save the table as ‘Table1’.

Next, we need to add a row to the table that will hold the number we want to increment. To do this, add the folowing data to Table1:

ID Number 1 0

Adding the ConnectionString
Now that we have a database setup we need to add a connection string to it. To do this, open up the Web.Config file for editing and add in the following between the and tags:

Adding the Default.aspx Page

Next, we will need to add a simple web form that has a label on it to show the number in the database and a button to call the SQL query to increment it. To do this:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a label onto the web form.
  8. Add a break line under the label.
  9. Drag and drop a button under the label.

Incrementing the Value

Next, we need to add some C# code that will actually increment the value in our database when the button is clicked. To do this, double click the button to generate the Button1_Click event method in the Default.aspx.cs code behind file. Then at the top of the class add in the following using statements:

Next, add the following code to the Button1_Click even method:

This will increment the number in the Number column, and then set our label to the value of that number in our database.


To test this out simply load up the web site and click the button a few times to ensure that the number in your database is being incremented and displayed in the label properly.
Download Source Files