Tuesday, July 30, 2013

ASP.NET Populate The DropDownList Control With The Northwind Categories Table

The Categories table is a perfect example of how sometimes you have to populate the DropDownList control to data from the database. In this example we will populate the DropDownList control to the Categories table in the Northwind database.

 1. Drag the DropDownList control into a .aspx page.
DropDownList Control

Make sure you check "Enable AutoPostBack" 2.  In your C# code file you need the namespaces

using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;

2. Then get the Northwind connection string value from the Web.config file
string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

3. Type in the following code in the Page_Load method
        protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (SqlConnection conn = new SqlConnection(connectString))
{
SqlCommand cmd = new SqlCommand("SELECT CategoryID, CategoryName
FROM Categories ORDER BY CategoryName", conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();

DropDownList1.DataValueField = "CategoryID";
DropDownList1.DataTextField = "CategoryName";
DropDownList1.DataSource = reader;
DropDownList1.DataBind();

reader.Close();

}
}
else
{
Response.Write("Selected item is " + DropDownList1.SelectedItem.Text + "<br>");
Response.Write("Selected id is " + DropDownList1.SelectedItem.Value + "<br>");
}
}
}

The line "if (!Page.IsPostBack)" is very important because if you don't have it you will never get the selected value. When you "Enable AutoPostBack" on the Designer view you tell ASP.NET to post back the page every time there is a change in the DropDownList1 control. So the block of code only executes once to populate the drop down list, after that only the "else" block is executed.

Monday, July 22, 2013

T-SQL: Stored Procedures (SELECT), SELECT By ID, Select Products by Supplier ID

In this example we will pass an input parameter to determine the result of the query.  We will pass in supplier id to get all the products that are provided by the supplier.

Here is the code
Use Northwind
GO
CREATE PROCEDURE dbo.selProductsBySupplierID
@SupplierID int
AS
SELECT DISTINCT p.ProductID,
p.ProductName,
p.UnitPrice
FROM Products p
INNER JOIN Suppliers s ON
p.SupplierID = @SupplierID
GO

The @SupplierID is the input parameter that the stored procedure expects, you use it in the join portion of the statement to match the SupplierID in the Products table. The DISTINCT keyword means that the query will only return one row in the result if there are duplicate rows.
Type the following to execute the stored procedure with the supplier id of 1
EXEC dbo.selProductsBySupplierID 1

The result should look like this
Select Northwind Product Results From T-SQL Select

Wednesday, July 17, 2013

ASP.NET: Call Stored Procedure Using SqlCommand and SqlDataReader

A lot of times you want to call a stored procedure quickly in the code to access the stored procedure.  You don't want to go through the trouble of dragging an SqlDataSource control in the design view just to use the stored procedure.

Here is how you would call the "Top Ten Most Expensive Products" stored procedure in the Northwind database.

1.  First you need the namespaces

using System.Web.Configuration;
using System.Data.SqlClient;
using System.Data;

2. Then get the Northwind connection string value from the Web.config file
string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

3. Now call the stored procedure and output the result from the SqlDataReader
  using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetProductsAvgPrice";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
Response.Write("Products Average Price is $" + (decimal)cmd.ExecuteScalar());
}

In the above code the ExecuteScalar() method executes a call to the stored procedure called "GetProductsAvgPrice" which uses the aggregate function AVG() to get the average products price. The only thing you have to watch out for is that you have to convert the type to the appropriate type if you want to use it. Since currency is of type decimal you want to use the result into a decimal value because the ExecuteScalar() method returns an object type.

Tuesday, July 16, 2013

ASP.NET: Programmatically Connect to The Database Using SqlConnection, DataReader and SqlCommand

So you have following connection string to the Northwind database in your Web.config and you want to connect to the database in the code behind instead using query builder.

  <connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.
SqlClient"/></connectionStrings>

Here is how you would do it

1. Get the connection from the Web.config file programmatically, you can look at this blog to find out how perform this step by step.  But here is the code to get the connection string from the Web.config file

string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;

2.  On the top of the file specify that you want to use the Sql.Data.SqlClient namespace by typing

using System.Data.SqlClient; 

3. Now type the following

 using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT ProductID,ProductName FROM Products", conn);
SqlDataReader dataReader = cmd.ExecuteReader();

try
{
while (dataReader.Read())
{
Response.Write("Product ID: " + dataReader["ProductID"] + dataReader["ProductName"] +
"<br>");
}
}
finally
{
dataReader.Close();
}

}
}
By using the "using" keyword you assure that the connection is automatically closed after the code is executed inside the using code block. So you don't have remember to close the connection string.
        using (SqlConnection conn = new SqlConnection(connectString))
Then you open the SqlConnection with
        conn.Open();

Then you create a new SqlCommand using the connection you've just opened
SqlCommand cmd = new SqlCommand("SELECT ProductID,ProductName FROM Products", conn);
Then to execute command to retrieve the data object SqlDataReader which will store your result in a read-only forward only stream of database rows.
            try
{
while (dataReader.Read())
{
Response.Write("Product ID: " + dataReader["ProductID"] +
dataReader["ProductName"] + "<br>");
}
}
finally
{
dataReader.Close();
}

The while loop loops through the reader until there is no more rows to read and print out the ProductID, and ProductName of each database row. Make sure you always use the SqlDataReader in a try block and always remember to close it since, it's a data stream.
This is a quick and easy way to query the database.

Monday, July 15, 2013

ASP.NET: Set Up SQL Server for ASP.NET Provider Databases

Out of the box the ASP.NET provider databases works with the local database file call aspnetdb.mdf, however in a production environment you cannot use this file because you need to work with the production database. To create the provider databases on a full version of SQL Server perform the following steps.

1. Navigate to the .NET Framework version that you want to use. Version 4.5 and Version 2 has the provider database wizard. I am using version 4.5 so the path is C:\Windows\Microsoft.NET\Framework\v4.0.30319

2. Double click on the file aspnet_regsql.exe, the ASP.NET SQL Server Setup Wizard will apear, click "Next" to continue

ASP.NET SQL Server Setup Wizard

3.  Select "Configure SQL Server for application services" radio button, then click next

Configure SQL Server for application services

4. Type in the database server name in the "Server:" field.  Make sure you type in the actual host name because if you type in (local) or localhost the database creation process will fail.   Leave the option as "Windows authentication" checked, unless you want to use SQL Server authentication.  Then click "Next" to continue.

Windows authentication

5.  Click next on the confirmation screen


6.  When the database has been successfully created you will see the message that says "The database has been created or modified"

The database has been created or modified

7. If you look at the Microsoft Management Studio you will see the aspnetdb database in the list of databases.

aspnetdb database in the list of databases

Now you have the databases necessary to work with the ASPNET provider services.  However, you still need to change the configuration file maching.config in the .NET folder in order for .NET to recognize that the database is available in the SQL Server database now or the web.config file in your web application.  The best practice is to change it in your web application so that it only affects your web application.  If you change the configuration in machine.config file you will change to for all the applications.

This example shows you how to use the AspNetSqlMembershipProvider

1. First add the connection string to the database, make sure you have the <clear/> tag right below the <connectionStrings> opening tag


  <connectionStrings>
<clear/>
<add name="aspnetdbConnectionString" connectionString="Data Source=(local);
Initial Catalog=aspnetdb;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

2. Now above the </system.web> tag type in the following

       <membership defaultProvider ="AspNetSqlMembershipProvider">
<providers>
<add name="AspNetSqlProfileProvider" connectionStringName="aspnetdbConnectionString"
applicationName="/" type="System.Web.Profile.SqlProfileProvider,
System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
Note: To make sure you have the right provider settings copy the declaration from your machine.config file and then just change the "connectionStringName" attribute.

Thursday, July 11, 2013

ASP.NET Configurations: Retrieve Multiple Connection Strings From The Current Web Application's Web.config File

So you have to work with multiple connection strings that you want to use in the Web.config file and you want to use it in the code behind file.    Below are the steps to retrieve multiple connection strings in the web.config file programmatically.

1. Make sure you have connection strings in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="AdventureWorksConnectionString" connectionString="Data Source=(local);
Initial Catalog=AdventureWorks;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>


2. Now in the Default.aspx.cs file type in the following in the top of the file, where all the using statements are to use the System.Web.Configuration namespace

using System.Web.Configuration;
using System.Configuration;

Obviously you can use it in any .cs file, the Default.aspx.cs is just an example.


3. In the Page_Load method type in the following line
ConnectionStringSettingsCollection connectStrings = WebConfigurationManager.ConnectionStrings;

foreach (ConnectionStringSettings cstr in connectStrings)
{
Response.Write(cstr.ConnectionString + "<br>");
}

Or you can just do this and you don't have to assign WebConfigurationManager.ConnectionStrings to a variable at all. A lot less typing.
        foreach (ConnectionStringSettings cstr in WebConfigurationManager.ConnectionStrings)
{
Response.Write(cstr.ConnectionString + "<br>");
}

If you run the code you will get the following

data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

Data Source=(local);Initial Catalog=Northwind;Integrated Security=True
Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True

Notice the attached SQLEXPRESS file aspnetdb.mdf file in your results, well it's because there's a
hierarchy in the Web.Config file and before .NET even look at the current Web.config  in your web application it looks in the .NET Framework install folder for the default Web.config file, this file is call the "Root Web" configuration level .  That's why the first item in the ConnectionStringSettingsCollection is not Northwind.

If you just want the current web applications Web.config connection strings section all you have to do is add the <clear/> tag right below the <connectionsStrings> opening tag in the current web application's Web.config file, like the xml code below.

  <connectionStrings>
<clear/>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="AdventureWorksConnectionString" connectionString="Data Source=(local);
Initial Catalog=AdventureWorks;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

The <clear/> tag tells .NET to remove all of the inherited configuration information and just use the configuration of the current web application.  So now the result will be

Data Source=(local);Initial Catalog=Northwind;Integrated Security=True
Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True

Which is what you really wanted in the first place.

Wednesday, July 10, 2013

ASP.NET Configurations: Retrieve Connection String Programmatically

So you have a connection string that you want to use in the Web.config file and you want to use in the code behind file.  You can do that with a single line of code in your .cs file.  Below are the steps to retrieve a connection string in the web.config file programmatically.

1. Make sure you have a connection string in your Web.config file.  A connection string looks something like this.

  <connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source=(local);
Initial Catalog=Northwind;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>


2. Now in the Default.aspx.cs file type in the following in the top of the file, where all the using statements are to use the System.Web.Configuration namespace
using System.Web.Configuration;
Obviously you can use it in any .cs file, the Default.aspx.cs is just an example.


3. In the Page_Load method type in the following line
    string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].
ConnectionString;
To display the connection string on your browser, type the following line
Response.Write(connectString);

Tuesday, July 9, 2013

ADO.NET: SqlDataSource Control

The SqlDataSource control provides you with a quick and easy way to access database data.  Most of the time you don't even have to write a single line of code.  Now this can a be a good thing and a bad thing, depends on how you look at things.  Most of the configuration and querying is performed via a configuration wizard.

Here are the steps to creating a SqlDataSource:

1. In a ASP.NET project/web site drag a SqlDataSource control in under "Data" in the "Toolbox" tab into a .aspx page.


After you dragged the control it should look like this on your .aspx page

SqlDataSource

2. Click on "SqlDataSource1" control, then click on the ">" sign, a slide out menu appears.  Select "Configure Data Source".

Configure Data Source

The "Configure Data Source" wizard will pop up.


Choose Your Data Connection

3. Click on the "New Connection" button, the "Add Connection" wizard will pop up. Select or type in your "Server name".  If you have a local instance of SQL Server, then you can type in "(local)" in the "Server name" field.  Leave the authentication method under "Log on to server" as "Windows Authentication"

Add Connection

The database in your SQL Server should be automatically populated, once you input the server name of database server in the "Server name" field.  Type in, or select the "Northwind" database.  You can test the connection by clicking on "Test Connection".  Once the connection is successful, click on the "OK" button.


4.  In the next step of the wizard a new connection has been created, and the connection string displayed.  Click "Next"

connection string

5.  In the next step the wizard will ask if you want to store connection string in the Web.config file.  Leave the checkbox checked, then you can change the name of the connection string in the text field.  Click "Next"

6.  At this point you have two options, either you can write your own SQL statement or stored procedures or specify the columns in a database table.  I always choose the first option which is "Specify a custom SQL statement or stored procedure" because in the next screen you will be given more options, and have the ability to work with more than one table.  You can still work with a single table if you choose this option, so it gives you more flexibility. Click "Next"


Configure the Select Statement

7.  You will be given the choice to create a custom SQL statement or to select a stored procedure.  In this example we will be building a custom Sql statement. So click on the "Query Builder" button.

Query Builder

8. The "Add Table" wizard will pop up.  Select the "Categories" and "Products" table.  Then click on the "Add" button and then the "Close" button.

Query Builder Add Table

9.  The selected tables populates the Query Builder wizard, as you can see the table relationships have been transferred over.

Query Builder wizard

10.  Select the "CategoryName" and "Description" in the "Categories" table.  Then the "ProductName" in the "Products" table.  The SQL select statement will change dynamically as you select a new column from the table window.

Query Builder wizard

11.  Click on the "Execute Query" button to execute the query and see the results.  Once you are happy with the results, click the "OK" button.

Query Builder Execute Query

12.  The select statement from "Query Builder" populates the "SELECT" tab in "Custom SQL Statement or Stored Procedures" wizard.

Custom SQL Statement or Stored Procedures" wizard

13. Click "Next", then click "Finish".  You now have the SqlDataSource control configured

The next step is to bind the data in the SqlDataSource control to a UI data control.  Lets use the GridView control.

1.  Drag the GridView control under "Data" in the "Toolbox" into a .aspx page.

Drag the GridView control under "Data" in the "Toolbox"
It should look like this when you have both controls on the page.

GridView control on .aspx page


2. At this point you can either bind the data from the SqlDataSource1 control to the GridView1 control via a wizard or write a little bit of code in the .aspx code behind page.  In this example since we have been using wizards the whole time I will use the wizard.  I will write a new blog on how to bind data programmatically in the future.  To bind the data to the GridView control via the wizard, click on the ">" button on the GridView1 control.

To bind the data to the GridView control via the wizard

3.In the "Choose Data Source:" drop down list, select "SqlDataSource1"

"Choose Data Source:" drop down list

Accept the default settings, then click on anywhere in on the page outside of the "GridView Tasks" wizard.

4.  Save the .aspx page, and then press F5 to run the web application.  The GridView control will display the data in the browser.

GridView control will display the data in the browser

Once again the SqlDataSource control is meant for beginners, and in situations where you need something quick and you can throwaway.  Such as a proof of concept in a client meeting, with Entity Framework and LINQ around, SqlDataSource is really not suitable for a full blown application anymore.

Source Code: SqlDataSourceWS.zip, click on "File" -> "Download" to download the .zip file


Monday, July 8, 2013

HTML5 Page Template

This is the bare minimum you need to write a HTML5 page:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
A little bit fancier, you want to specify the language and character set:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>

</body>
</html>

HTML5 Tags


Not Supported in HTML5:
  • <tt>
  • <strike>
  • <noframes>
  • <frame>
  • <frameset>
  • <dir>
  • <center>
  • <big>
  • <basefont>
  • <applet>
  • <acronym>


 

DOCTYPE tag:

  • HTML5:
    <!DOCTYPE html>

  • HTML 4:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  • XHTML Strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  • XHTML Traditional:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


New HTML5 Tags:

Layout:
  • Top area of the page:
    <header>
  • Bottom area of the page:
    <footer>
  • Navigation links:
    <nav>
  • Line breaks:
    <wbr>


UI:
  • Progress bar, shows defined progress with flashing light:
    <progress>
  • Show result of a calculation:
    <output>
  • Meter (like a progress bar) but no flashing light:
    <meter>


Language:
  • Ruby annotation (East Asian typography):
    <ruby>
  • What to display if ruby annotation is not supported:
    <rp>
  • Definition/pronunciation of characters (East Asian typography):
    <rt>


Security:
  • Key pair generator, the public key is sent to the server:
    <keygen>


Data Type:
  • Date and Time:
    <time>


Event Handling:
  • Invokes a command for a button or html element, such as a Javascript function (only supported in IE9):
    <command>


External Application/Objects:
  • Embed external objects/content that sometimes requires a plugin such as Flash contents :
    <embed>


Media:
  • Sound content:
    <audio>
  • Video content:
    <video>
  • Subtitles for video or audio:
    <track>
  • List of sources(different media formats) for video or audio, the browser will play the supported video format:
    <sources>


Graphics:
  • Like a painting canvas that you can fill with graphics via scripting usually Javascript on the fly:
    <canvas>


Content:
  • Details the user can expand and collapse:
    <details>
    Details tag in Firefox Version 22.0:

    Details tag in IE 10.0.9200.16618:


    Details tag in Chrome Version 27.0.1453.116 m:

    Collapsed View In Chrome:

     


    Expanded View In Chrome:



  • Text next to the arrow in <details> tag:
    <summary>
  • Grouping of cotent, usually used in conjunction with <figcaption> to display an image with a caption:
    <figure>
  • Caption for &ltfigure&gt tag:
    <figcaption>
  • Format text in a different direction than adjacent text:
    <bdi>
  • Section of the page:
    <section>
  • A caption:
    <caption>
  • A content item:
    <article>
  • Related content item:
    <aside>
  • Highlight text:
    <mark>
  • Dialog box or window, a markup of conversions (not the dialog window more of like a transcript of a chat):
    <dialog>

Friday, July 5, 2013

Entity Framework Part 1: Generate an Entity Framework for the Northwind Database Tables

In my previous post we've created the Northwind products page using the SqlDataSource data control, even though there's nothing wrong with the solution.  SqlDataSource is a an old technology and is not meant to be an enterprise solution.  SqlDataSource is the stone age of .NET data access technology.  The future of .NET is the Entity Framework.

The goal of the Entity Framework is to create a conceptual model of your data store so that you can work with tables and rows as objects, or entities.  In essence the developer does not know or care what the data store is, he does not have to be a dba to work with the data.

To demonstrate the Entity Framework let's create the Northwind products page using the Entity Data Model of the Northwind database.

Here are the steps:

1. Open the Northwind project you created with the SqlDataSource
2. Righ-click on the Northwind project in "Solution Explorer", then select "Add", then "New Item"
Solution Explorer
3. Select "Data" under "Visual C#" in the "Add New Item" dialog box, then select "ADO.NET Entity Data Model"



4. In the "Choose Model Contents" dialog box, choose "Generate from database", then click "Next"

Generate from database


 5. On the "Choose Your Data Connection" dialog box, click on the "New Connection" button, then type in the name of your database server in the "Server name:" field and select the "Northwind" database in the "Connection Properties" dialog box.
Connection Properties

 6. Select the "Northwind" database connection, and save the Entity connection as "NorthwindEntities", then click "Next"

Entity Data Model Wizard
 7. Choose all of the database tables in the "Choose Your Database Objects and Settings" dialog box, leave the "Model Namespace", then click "Finish".  Entity Framework for the "Northwind" database model will be generated for you in Visual Studio.

Northwind database model


 8. In "Solution Explorer" there is also a "NorthwindModel.edmx" file that contains the Entity and data store mappings in raw XML.

9. Now to query the Northwind model you need to use LINQ, create a new Web Form and call it Products.aspx

10. Add a GridView to the design surface

11. Open the code-behind page Products.aspx.cs then in the Page_Load method type in the following
        

       protected void Page_Load(object sender, EventArgs e)
        {
            NorthwindEntities nEntitites = new NorthwindEntities();

            var products = nEntitites.Products;

            GridView1.DataSource = products;
            GridView1.DataBind();

        }

        In the code above you instantiate a new NorthwindEntities model, then assign the Products collection into the variable products.  The Products entity contains a collection of the Product object, it's like querying the Products table but you are working directly with the object created by the Entity Framework instead querying the database directly.

12.  To run the application press F5, you will see that the GridView control has been populated with data

GridView

Source Code: Northwind.zip, click "File" -> "Download" to download the source code in .zip format.

Thursday, July 4, 2013

ASP.NET: Installing IIS 7

You can use Visual Studio for all of your web server needs for local development, but it's essential that you familiar yourself with a full blown IIS version.  In this tutorial I will show how to install IIS on a Windows 7 machine.

1. Open the "Control Panel"
2. Select "Programs and Features"

3.  Click on "Turn Windows features on or off"

Turn Windows features on or off
4.  In the "Windows Features" dialog box, select "Internet Information Services" option, then click "OK"

Internet Information Services

5. To manage the IIS instance on the machine type "mmc" into the start menu then press "Enter", the click "Yes" this will bring up the "Microsoft Management Console"

Microsoft Management Console

6. Click on "File" then "Add/Remove Snap in" or Ctrl+M
7. Select "Internet Information Services (IIS) Manager" snap-in in the "Available snap-ins:" dialog box
Internet Information Services (IIS) Manager

8. Click "Add", then click "OK"
9. Click on the "Internet Information Services (IIS) Manager" node on the right hand side to manage your IIS instance
Internet Information Services (IIS) Manager



Wednesday, July 3, 2013

ASP.NET: Northwind Products Page

I could go on, and on about ASP.NET features and how awesome it is, but most of the time you come to a blog to learn about real world situations.  So why not create a web application base on the Northwind database.

Just from looking at the database tables we know that we could divide the web site into two sections. The e-commerce side of the business and then the internal side of the business. So the e-commerce site deals with the products are being offered by the Northwind corporation, and the internal side of the site deals with the sales team and the employees.

So our first task is to create a products page that displays the products for the Northwind web site.

1. Create an empty web application call "Northwind"
2. Add a "Web Form" and call it Default.aspx to the project
3. Click on the "Design" tab in main window of Visual Studio
Visual Studio Web Form Design Surface

4. Click on the "Toolbox" tab, then expand the "Data" node, then drag the "GridView" data control to the Design surface.  The Design Surface is the big window in the middle of Visual Studio.
GridView
5. Click on "Toolbox" tab again, this time drag the "SqlDataSource" control to the Design Surface

SqlDataSource
6. Click on the ">" button next to SqlDataSource1 control, then select "Configure Data Source"
7. Click on the "New Connection" button
Visual Studio Configure Data Connection
 8. Select your "Server name", SQL Server should pick up your database server automatically if it's on a local machine, but if it doesn't type in (local) in the "Server name" field.


9. Click "OK"
10. A new connection has been defined in your web application
Visual Studio Add Connection
11. Click "Next", leave the checkbox check for the option "Yes, save this connection as:", "NorthwindConnectionString"
12. Click "Next"
13. On the "Configure the Select Statement" window select "Specify a custom SQL statement or stored procedure"
Configure the Select Statement
 14. Click "Next"
15. Click on the "Query Builder" button"
 16. On the "Add Table" window select the "Categories" and "Products" table and then click "Add", then click "Close"
Query Builder

17. In "Query Builder" the two tables and their relationships are displayed
Query Builder Relationships

18. The following into the SELECT statement window

SELECT        Products.ProductName, Products.UnitPrice, Categories.CategoryName, Categories.Description
FROM            Categories INNER JOIN
                         Products ON Categories.CategoryID = Products.CategoryID
Query Builder Select Statement Window

19. Click "OK"
20. Click "Next"
21. Click "Finish"
22. Click on the ">" button next to the GridView1 control, and for the "Choose Data Source" dropdown list chose "SqlDataSource1"
23. Right-click on the "Default.aspx" file then select "Set as Start Page"
24. Press F5 to run the page, the GridView will be displayed on the browser page.

GridView

This page uses the SqlDataSource data control, in real world situation you will probably never use this data control in a modern application.  However, you might run into this data control in older applications that still uses .NET 1.1 or .NET 2.0.  It also comes in handy if you have to throw something together quick and dirty like a throw away code or a quick demo.

 In this tutorial we added the GridView UI data control and bind it to the SqlDataSource data control.  Very simple, it is a good solution if you are not at a stage that you don't need a full blown data access layer like the Entity Framework just yet.