Download as pdf or txt
Download as pdf or txt
You are on page 1of 0

Beginning ASP.

NET & SQL Server 2005 Express



[ Home ] [ Part 1] [ Part 2 ]

Tutorial 01 - Creating a new Web site in Visual Studio 2005
Turorial 02 - Creating a new SQL Database in Visual Studio
Tutorial 03 - Adding Table to SQL Database
Tutorial 04 - Adding Pages
Tutorial 05 - Connecting to SQL Database and Executing Select Commands
Tutorial 06 - Executing Insert Command
Tutorial 07 - Executing Modify Command
Tutorial 08 - Executing Delete Command

Tutorial 01 - Creating a new Web site in Visual Studio 2005
1. Choose the File New Web Site command.

2. Choose ASP.NET Web Site from the list of available templates.
3. Choose File System from the Location drop-down list.
4. Enter the location for the Web site, C:\ASPNETSQL in the combo box thats to the right of the Location drop-down list.
5. Choose the language, Visual C# to create the site.
6. Click OK.
Back to Top
Turorial 02 - Creating a new SQL Database in Visual Studio
1. In the Solution Explorer panel, right Click App_Data folder Add New Item.
2. Make sure SQL Database is selected in the Templates box.
Page 1 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx

3. Enter a name for the SQL Database in the Name text box.
4. Click Add.
Back to Top
Tutorial 03 - Adding Table to SQL Database
1. Double click Database.mdf in the Solution Explorer panel to open the Server Explorer panel.

2. In the Server Explorer, right click Tables Add New Table.
3. Fill in the the values as shown in the figure below to the table.

4. Right click the first row and set [ID] as primary key.
Page 2 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx

5. Set the following [ID] properties as shown in the figure below.

6. Choose the File Save Table command.

7. In the Server Explorer, right click [Members] Show Table Data to fill in some values.

8. Save the [Members] table.
Back to Top
Tutorial 04 - Adding Pages
1. In the Solution Explorer panel, Right Click Website Add New Item.
Page 3 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx

2. Make sure Web Form is selected in the Templates box.
3. Enter a name for the page in the Name text box.
4. Select the programming language.
5. Make sure the Place Code in Separate File option is checked.
6. Click Add.
Back to Top
Tutorial 05 - Connecting to SQL Database and Executing Select Commands
In this section you'll see examples of connecting a SQL database.To interact with SQL database in your program, you use classes from the
System.Data.SqlClient namespace. You connect to a SQL database using a SqlConnection object-with a connection string of the
following format:
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";
where AttachDBFilename is the directory and filename of your SQL database.
The following example creates an SqlConnection object, passing connectionString (set in the previous line of code) to the constructor:
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

A SELECT statement using the ExecuteReader() method. This method returns the result set in a DataReader object, which you can then use
to read the rows returned by the database.
You'll notice that I didn't call the Open() method of the SqlConnection object until just before calling the ExecuteReader() method of the
SqlCommand object. This is intentional. By opening the connection at the very last moment, you minimize time spent connected to the database and
therefore conserve database resources.
The result set returned by SqlCommand is stored in SqlDataReader. You then read the rows from SqlDataReader using the Read() method.
This method returns the Boolean true value when there is another row to read, otherwise it returns false.
You can read an individual column value in a row from SqlDataReader by passing the name of the column in square brackets. For example, to read
the [ID] column, you use dr["ID"]. You can also specify the column you want to get by passing a numeric value in brackets. For example, dr[0] also
returns the [ID] column value. 0 corresponds to the first column in the table, which in this example is the [ID] column.
1. Create a Web Form called View.aspx.
2. Drag and drop 1 Label Control onto the WebForm.
3. Double click on the Web Form and type the following codes.
protected void Page_Load(object sender, EventArgs e)
{
// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
Page 4 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx
4. Open this page (View.aspx) in the Web browser.
Back to Top
Tutorial 06 - Executing Insert Command
You can use the ExecuteNonQuery() method of a Command object to execute any command that doesn't return a result set from the database. In
this section, you'll learn how to use the ExecuteNonQuery() method to execute commands that modify information in the database. The
ExecuteNonQuery() method returns an int value that indicates the number of rows affected by the command.
1. Create a Web Form called Add.aspx.
2. Drop 2 Textbox controls, 2 DropDownList controls and 1 button controls on your form and arrange the controls as shown in Add.aspx.
3. Add the values, M & F to the DropDownList control for Gender accordingly.
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// set the CommandText property of the SqlCommand object to
// the SELECT statement
cmd.CommandText = "SELECT * FROM [Members]";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SQL SELECT statement
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

this.Label1.Text = "";

// read the rows from the sqlDataReader object using
// the Read() method
while (dr.Read())
{
this.Label1.Text = this.Label1.Text
+ "ID: " + dr["ID"].ToString() + "<br>"
+ "First Name: " + dr["FirstName"].ToString() + "<br>"
+ "Last Name: " + dr["LastName"].ToString() + "<br>"
+ "Gender: " + dr["Gender"].ToString() + "<br>"
+ "Year Born: " +dr["YearBorn"].ToString() + "<br><br>";
}

// close the SqlDataReader object using the Close() method
dr.Close();

// close the SqlConnection object using the Close() method
conn.Close();
}
Page 5 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx

4. Double click on the Web Form and and type the following codes to fill the DropDownList for Year Born during page load.
5. Double click on the Button and type the following code:
protected void Page_Load(object sender, EventArgs e)
{
// append item to the collection
for (int i = 1900; i <= 2007; i++)
this.DropDownList2.Items.Add(i.ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// add a collection of parameters associated with a SqlCommand
cmd.Parameters.Add("FirstName", SqlDbType.NChar);
cmd.Parameters["FirstName"].Value = this.TextBox1.Text;
cmd.Parameters.Add("LastName", SqlDbType.NChar);
cmd.Parameters["LastName"].Value = this.TextBox2.Text;
cmd.Parameters.Add("Gender", SqlDbType.NChar);
cmd.Parameters["Gender"].Value = this.DropDownList1.Text;
cmd.Parameters.Add("YearBorn", SqlDbType.NChar);
cmd.Parameters["YearBorn"].Value = this.DropDownList2.Text;

// set the CommandText property of the SqlCommand object to
// the INSERT statement
cmd.CommandText = "INSERT INTO [Members] ([FirstName], [LastName], [Gender], [YearBorn]) VALUES
(@FirstName, @LastName, @Gender, @YearBorn)";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the INSERT statement
int numberOfRows = cmd.ExecuteNonQuery();

// close the SqlConnection object using the Close() method
conn.Close();
Page 6 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx
6. Open this page (Add.aspx) in the Web browser.
Back to Top
Tutorial 07 - Executing Modify Command
1. Create a Web Form called Modify.aspx.
2. Drop 2 Textbox controls, 3 DropDownList controls and 1 button controls on your form and arrange the controls as shown in Modify.aspx.
3. Double click on the Web Form and type the following startup code for the page in the Page_Load event handler.
4. Set the DropDownList1.AutoPostBack property to true.
5. Double click the DropDownList1 and type the following code for the DropDownList_SelectedIndexChanged event handler.

// redirect to View.aspx
Response.Redirect("View.aspx");
}
protected void Page_Load(object sender, EventArgs e)
{
// check whether the page is being loaded in response to a client postback
if (Page.IsPostBack)
return;

// append ListItem to the collection
for (int i = 1900; i <= 2007; i++)
this.DropDownList3.Items.Add(i.ToString());

// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// set the CommandText property of the SqlCommand object to
// the SELECT statement
cmd.CommandText = "SELECT [ID] FROM [Members]";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SQL SELECT statement
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

// read the rows from the sqlDataReader object using
// the Read() method
while (dr.Read())
{
// append ListItem to the collection
this.DropDownList1.Items.Add(dr["ID"].ToString());
}

// close the SqlDataReader object using the Close() method
dr.Close();

// close the SqlConnection object using the Close() method
conn.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

//
cmd.Parameters.Add("ID", SqlDbType.Int);
Page 7 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx
6. Add the Page_SaveStateComplete event handler to display the first row values.
7. Double click the button and type the following code for Button_Click event handler.
8. Open this page (Modify.aspx) in the Web browser.
cmd.Parameters["ID"].Value = this.DropDownList1.Text;

// set the CommandText property of the SqlCommand object to
// the SELECT statement
cmd.CommandText = "SELECT * FROM [Members] WHERE [ID] = @ID";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SQL SELECT statement
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

// read the rows from the sqlDataReader object using
// the Read() method
while (dr.Read())
{
this.TextBox1.Text = dr["FirstName"].ToString();
this.TextBox2.Text = dr["LastName"].ToString();
this.DropDownList2.Text = dr["Gender"].ToString();
this.DropDownList3.Text = dr["YearBorn"].ToString();
}

// close the SqlDataReader object using the Close() method
dr.Close();

// close the SqlConnection object using the Close() method
conn.Close();
}
protected void Page_SaveStateComplete(object sender, EventArgs e)
{
// display the first row values
this.DropDownList1_SelectedIndexChanged(null, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// add a collection of parameters associated with a SqlCommand
cmd.Parameters.Add("ID", SqlDbType.NChar);
cmd.Parameters["ID"].Value = this.DropDownList1.Text;
cmd.Parameters.Add("FirstName", SqlDbType.NChar);
cmd.Parameters["FirstName"].Value = this.TextBox1.Text;
cmd.Parameters.Add("LastName", SqlDbType.NChar);
cmd.Parameters["LastName"].Value = this.TextBox2.Text;
cmd.Parameters.Add("Gender", SqlDbType.NChar);
cmd.Parameters["Gender"].Value = this.DropDownList2.Text;
cmd.Parameters.Add("YearBorn", SqlDbType.NChar);
cmd.Parameters["YearBorn"].Value = this.DropDownList3.Text;

// set the CommandText property of the SqlCommand object to
// the UPDATE statement
cmd.CommandText = "UPDATE [Members] SET [FirstName] = @FirstName, [LastName] = @LastName, [Gender] =
@Gender, [YearBorn] = @YearBorn WHERE [ID] = @ID";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the INSERT statement
int numberOfRows = cmd.ExecuteNonQuery();

// close the SqlConnection object using the Close() method
conn.Close();

// redirect to View.aspx
Response.Redirect("View.aspx");
}
Page 8 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx
Back to Top
Tutorial 08 - Executing Delete Command
1. Create a Web Form called Remove.aspx.
2. Drop 1 DropDownList controls, 1 button and 1 Label controls on your form and arrange the controls as shown in Remove.aspx.
3. Double click on the Web Form and and type the following startup code for the page in the Page_Load event handler.
4. Double click the button and type the following code for Button_Click event handler.
5. Double click the button and type the following code for Button_Click event handler.
protected void Page_Load(object sender, EventArgs e)
{
// check whether the page is being loaded in response to a client postback
if (Page.IsPostBack)
return;

// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// set the CommandText property of the SqlCommand object to
// the SELECT statement
cmd.CommandText = "SELECT * FROM [Members]";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// create a SqlDataReader object and call the ExecuteReader()
// method of the SqlCommand object to run the SQL SELECT statement
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

// set label to empty
this.Label1.Text = "";

// read the rows from the sqlDataReader object using
// the Read() method
while (dr.Read())
{
// Display row
this.Label1.Text = this.Label1.Text
+ "ID: " + dr["ID"].ToString() + "<br>"
+ "First Name: " + dr["FirstName"].ToString() + "<br>"
+ "Last Name: " + dr["LastName"].ToString() + "<br>"
+ "Gender: " + dr["Gender"].ToString() + "<br>"
+ "Year Born: " + dr["YearBorn"].ToString() + "<br><br>";

// append ListItem to the collection
this.DropDownList1.Items.Add(dr["ID"].ToString());
}

// close the SqlDataReader object using the Close() method
dr.Close();

// close the SqlConnection object using the Close() method
conn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
// formulate a string containing the details of
// the database connection
string connectionString = "Data Source=.\\SQLEXPRESS;"
+ "AttachDbFilename=\"C:\\ASPNETSQL\\App_Data\\Database.mdf\";"
+ "Integrated Security=True;"
+ "Connect Timeout=30;"
+ "User Instance=True";

// create a SqlConnection object to connect to the database
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);

// create a SqlCommand object
System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();

// add a collection of parameters associated with a SqlCommand
cmd.Parameters.Add("ID", SqlDbType.NChar);
cmd.Parameters["ID"].Value = this.DropDownList1.Text;
Page 9 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx
6. Open this page (Remove.aspx) in the Web browser.
Back to Top
2007 WCW

// set the CommandText property of the SqlCommand object to
// the DELETE statement
cmd.CommandText = "DELETE FROM [Members] WHERE [ID] = @ID";

// open the database connection using the Open() method of the SqlConnection object
conn.Open();

// call the ExecuteNonQuery() method of the SqlCommand object
// to run the INSERT statement
int numberOfRows = cmd.ExecuteNonQuery();

// close the SqlConnection object using the Close() method
conn.Close();

// redirect to View.aspx
Response.Redirect("Remove.aspx");
}
Page 10 of 10 Untitled Page
5/28/2008 http://localhost:50078/ASPNETSQL/Beginner.aspx

You might also like