ASP.NET Basics with Visual Studio Web Developer 2008

Posted by – January 8, 2009

ASP.NET is one of the key technologies behind .NET Framework, you can easily create web applications to collect data entered by user by placing some input controls in your page, once the data is entered and the page is submited, you can read data on server side by accessing specific properties in your controls.

This article will give an idea about how to create a simple ASP.NET project, it will have a page that contains some textboxes and a button, this button will have an event attached to it, we will add some code in this event to store user entered data into an SQLite database using its ADO.NET provider that can be downloaded here.

I’m assuming that you already have installed Visual Studio Web Developer Express 2008 in your computer, if not, you must download both from this site.

Now you must start Visual Studio Web Developer Express 2008 and then go to File->New Web Site… menu like we have in the image below:

new_project_menu

A window will be opened to select the project template used to create your website please select “ASP.NET Web Site”:

new_website_wizard

The project will be created and opened, you will see Default.aspx markup code, but we won’t write any markup code by now, we will open this file in design mode to drag and drop ASP.NET controls on page.

Please go to View->Solution Explorer menu and right click on Default.aspx and select “View design”:

view_design

In design mode when can modify the page visually, we can add more controls by just drag and drop controls on page and you only need point and click on all controls to modify its properties or to add events.

Please go to View->Toolbox menu to show the control toolbox:

toolbox

You can drag some controls into the page now, please drag the label control from toolbox to the page, now go to toolbox again and click on textbox control and drag it into the page too.

Press enter add repeat the steps above in this new line by adding another label and another textbox, press enter twice to insert two new lines, go to toolbox an drag a button control to the page.

page_design_mode

We also need change some control attributes, like control identifier and text to be displayed a control label, you can do it by click on control in design mode and then changing these properties at “Properties Window” at View->Properties Window menu.

properties

Once all properties of controls on page is properly set, we must set the event to be triggered when the user clicks on button in this page, in order to do it, please do a double click on button in design mode, this will open the Default.aspx.cs an add the btnSave_Click method to _Default class:

Default.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /*
    The method below will act as button click event handler,
    this event was added after a double click on the button
    in design mode, this event will be called every time when you
    click in the button on your page.
    */

    protected void btnSave_Click(object sender, EventArgs e)
    {

    }
}

If you go to View->Solution Explorer menu and do a right click on Default.aspx to select “View markup” you will see the code below:

Default.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!--
In the line below we are specifying C# as .NET language used with this page in "Language" page attribute, in "CodeFile" attribute  you will specify the file that contains all server side code of this page (controls, events and variables).
-->
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <!--
   All ASP.NET controls must be placed inside a form control.
   -->
    <form id="form1" runat="server">
    <div>
        <!--
       This is a simple label control that just output text.
       -->
        <asp:Label ID="lblName" runat="server" Text="Name"/>

        <!--
       The textbox control will allow us to input data on page.
       -->
        <asp:TextBox ID="txtName" runat="server"/>
        <br />

        <asp:Label ID="lblAddress" runat="server" Text="Address"/>
        <asp:TextBox ID="txtAddress" runat="server"/>
        <br />
        <br />

        <!--
       This button will allow us to submit data to the server.
       Once clicked it will call btnSave_Click event on server
       to handle this data, we can make it happens by
       specifying the onclick attribute.
       -->
        <asp:Button ID="btnSave" runat="server"
            onclick="btnSave_Click" Text="Save" />
    </div>
    </form>
</body>
</html>

Now click on View->Solution Explorer menu and then do a right click on project name and select “Add Reference…” context menu like below:

add_reference_menu

This will open the “Add Reference…” window, click on “Browse” tab and navigate to the folder where you extracted the zip containing SQLite binaries. Once you have found this folder, select System.Data.SQLite.DLL file and click on “Ok” button to add this file as project reference.

add_reference_window

Please go to View->Solution Explorer menu and right click on Default.aspx and select “View code”:

view_code

It’s time to add some bussiness logic to button click event, please go to button click method and put the code below on method body:

Default.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/*
 * We must also import there two namespaces to use
 * ADO.NET common classes and SQLite data provider.
 */

using System.Data.Common;
using System.Data.SQLite;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    /*
     * All the code added in this event is related with persistence of
     * data provided by user in textboxes on page, when the user clicks
     * on save button in page the data typed on textboxes will be
     * avaliable on this event by accessing the "Text" property of both
     * txtName and txtAddress objects, these objects holds a reference
     * to TextBox controls containing contact name and its address.
     */

    protected void btnSave_Click(object sender, EventArgs e)
    {
        /*
         * Getting a DbProviderFactory reference, this factory
         * will be used to create database connection using this
         * ado.net provider.
         */

        DbProviderFactory fact = DbProviderFactories
            .GetFactory("System.Data.SQLite");
       
        /*
         * Creating a DbConnection that will allow this code to connect
         * on sqlite database.
         */

        using (DbConnection cnn = fact.CreateConnection())
        {
            /*
             * Setting the database connection parameters, in the
             * example below we are setting the data source parameter
             * that contains the path of database file.
             */

            cnn.ConnectionString = "Data Source=c:\\contact.db3";
           
            //Opening database connection
            cnn.Open();
           
            /*
             * Now we will create a DbCommand instance to allow this code
             * to send and execute sql command on database.
             */

            using (DbCommand cmd = cnn.CreateCommand())
            {
                /*
                 * Create a contact table with three fields:
                 * id, name and address.
                 */

                cmd.CommandText = "CREATE TABLE IF NOT EXISTS contact(id int primary key, name varchar, address varchar);";

                /*
                 * Now we will execute the sql statement above to
                 * create the contact table on database.
                 */

                cmd.ExecuteNonQuery();

                /*
                 * Setting the SQL command to be used to insert a
                 * new contact into database.
                 */

                cmd.CommandText = "INSERT INTO contact(name, address) values (?, ?);";

                /*
                 * We use a SQLiteParameter to supply data on SQL
                 * statements, once defined, the parameter value
                 * will replace the ? symbol in sql commands.
                 */

                SQLiteParameter myparam;

                /*
                 * Creating a new database parameter instance once you
                 * have a parameter defined the value of this parameter
                 * will replace the ? symbol in the SQL command specified
                 * above.
                 */

                myparam = new SQLiteParameter();
               
                //Setting parameter value.
                myparam.Value = txtName.Text;
               
                //Adding parameter to the sql command.
                cmd.Parameters.Add(myparam);

                /*
                 * Creating a new database parameter instance once you
                 * have a parameter defined the value of this parameter
                 * will replace the ? symbol in the SQL command specified
                 * above.
                 */

                myparam = new SQLiteParameter();
               
                //Setting parameter value.
                myparam.Value = txtAddress.Text;
               
                //Adding parameter to the sql command.
                cmd.Parameters.Add(myparam);

                /*
                 * Now we will execute the sql statement above to  
                 * insert a new contact into contact table.
                 */

                cmd.ExecuteNonQuery();
            }
        }
    }
}

Now you can test the application, just go to Debug->Start Debugging, visual studio will start a web server and then a internet explorer window will be opened and Default.aspx page will be loaded. Now you are ready to try your first ASP.NET application!

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>