In the third of a series of five articles exploring Microsoft Web technologies I'll walk you through building a simple Web application which retrieves and stores data in a SQL database.
First off you need to set up your development environment, to find out how see my previous article.
I'm going to show you how to build a simple address book application which will allow you to search for a contact by name and add new contacts. The data will be stored in a SQL database and the frontend will be built using ASP.NET.
To kick off you need to open Visual Studio and create a new Web Site:
(If the Solution Explorer is not displayed press Ctrl + S + W)
(If the Server Explorer is not displayed press Ctrl + S + L)
We now have our database ready to use so its time to link it to our web app and build a simple frontend.
You will now get a wizard pop up which will walk you through the creation of your Dataset.
1: DataSet1TableAdapters.addressBookTableAdapter addressAdapter = new DataSet1TableAdapters.addressBookTableAdapter();
2: DataSet1.addressBookDataTable addresses = addressAdapter.GetData();
3:
4: foreach (DataSet1.addressBookRow addressRow in addresses)
5: {
6: Response.Write(addressRow.Name + "/" + addressRow.Phone);
7: }
Once you've got your code working and everything compiles we have a way to retrieve all the data from the database and display it. The code can be modified slightly to display only results matching what was entered in the search box with the addition of an if statement:
6: if (searchBox.Text == addressRow.Name)
7: Response.Write(addressRow.Name + "/" + addressRow.Phone);
8: }
This is the quickest way to implement search functionality for this example but it would be much more elegant to construct a SQL query based on the search term to avoid iterating over all data in the table.
Now we have our database and means of getting data out implemented it just leaves the small task of implementing the ability to put some data in!
2: addressAdapter.InsertQuery(nameBox.Text,phoneBox.Text);
3: Response.Write(nameBox.Text + " and " + phoneBox.Text + " written to database!");
If you hit F5 it will compile and run and you should be able insert data and then search it.
If you get stuck check out the below video of me building the application from start to finish.
We will be looking at building a Silverlight front end for our address book database.