IS 460 ASP.NET Lab (Database Introduction) Ekedahl In this lab

advertisement
IS 460
ASP.NET Lab (Database Introduction)
Ekedahl
In this lab, you will use the database named Invoice.mdb having the following schema:
As you can see from the above figure, the database has three tables. Once customer has many invoices, which may have
many invoice items. As we progress, you will see how to work with one to many relations and the intricacies of data
binding with one-to-many relationships.
In this lab, you work with the following topics:



Create an empty Web site as you have done before.
Configure an SqlDataSource to work with a database table.
Bind a GridView control to the SqlDataSource so as to display it’s records
Lab Exercise (Preparation) – Creating the Web Site
1. Create a new ASP.NET Web project. I suggest that you create an Empty Web Site so as to avoid the clutter of
all of the temps. The instructions will not match if you create a Web site from the template.
2. Using the Solution Explorer, create a folder named App_Data. To create a folder, right click the project name in
the Solution Explorer. From the context menu, click Add / New Folder. Rename the folder, as necessary. Note
that this folder is created automatically when you use the default template.
3. Copy the database named Invoice.mdb from the Lecture Notes page on my Web site into the App_Data folder
of your project directory.
4. Click the Refresh button at the top of the Solution Explorer. The database named Invoice.mdb should appear in
the Solution Explorer’s App_Data folder as shown in the following figure. If not, manually add the item to the
1|Page
project. You will need this database for all of the subsequent exercises.
Lab Exercise 1 – Creating an SqlDataSource
In this first exercise, you will create an SqlDataSource on a form and bind a GridView control to that data source.
1. Create the default form (Default.aspx) in the project.
Visual Studio 2012 no longer supports the AccessDataSource for Web projects forcing you to use the
SQLDataSource for database access. This does not pose a problem because the SQL data source can be used to
connect to Access databases in addition to native SQL Server databases. There are some tricks to use the
AccessDataSource but I’ll avoid them here.
2. Create an SqlDataSource control on the default form (Default.aspx) such that it will connect to the database
named Invoice.mdb. On the right side of the control in the Design window, you should see a small arrow. Click
this arrow and then click Configure Data source to begin the configuration process as shown in the following
figure:
Note that you can configure all of this manually, or use the configurator (wizard) and then modify the
configuration as you see fit.
3. In the first dialog box that appears, you will begin to create the Connection string that the control will use to
connect to the database. Click the New Connection button as shown in the following figure:
2|Page
4. The following figure appears.
5. If the Data source is not set to Microsoft Access Database File (OLE DB), click the Change button and select the
Access database from the following dialog box:
3|Page
6. Click OK, to select the database type.
7. Click the Browse button to select the database name. Select the Invoices.mdb file from the App_Data folder.
8. Click the Test Connection button to verify that the connection is working correctly. You should see the following
dialog box:
9. Click OK to create the connection. It should appear similar to the following figure:
The wizard that you just used created the connection string for you. You can create as many connection strings
as you need for an application. However, you only need one for each database.
10. Click Next to continue configuring the data source. The following dialog box appears:
4|Page
11. If you check the check box, Visual Studio will create the connection string in the web.config file and reference
that web.config entry from the SqlDataSource. You can name the connection string anything you want so long
as the name is a valid variable name. Make sure the check box is checked and click the Next button do display
the following dialog box.
12. In the following dialog box, you need to specify the table(s) or querie(s) that you want to use. Select the table
named tblCustomers and the select each field individually as shown in the following figure:
13. In the above dialog box, click the Advanced tab. This causes the following dialog box to appear:
5|Page
14. Check the box as shown. This causes the system to generate the code to perform INSERT, UPDATE, and DELETE
statements. Note that a primary key must be defined for the table for this to work. Click OK to close this dialog
box. Note also that you can add WHERE and ORDER BY clauses to the SELECT statements in this dialog.
15. In the next dialog box, click the Test Query button to verify that the query works and is returning rows.
16. Click Finish to generate the code. Note that it takes a few seconds for the code generator to do its job.
17. Take a close look at the code generated by the tool. You will see that the SqlDataSource now contains the
necessary insert, update, and delete commands, along with the parameters for those commands as shown in
the following figure:
6|Page
THE FOLLOWING IS IMPORTANT AND DISCUSSES THE CONCEPT OF A CODE RENDER BLOCK. WE WILL WORK WITH
CODE RENDER BLOCKS EXTENSIVELY DURING THE DATABASE PORTION OF THIS COURSE:
Note that the ConnectionString attribute contains the following “interesting” syntax:
ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
Any code embedded inside the <% and %> characters is called a code render block. This code, even though it appears in
the .aspx file, is processed by the server. There are various forms of code render blocks as follows:

<% inline code %> causes host language code to be executed when encountered by the ASP.NET worker
process. These are self-contained code blocks (statements). For example, the following will write “hello” to the
output stream:
<% Response.Write(“Hello”); %>.
The syntax of the code in a code render block must match the programming language depicted in the @Page
block.

<%= inline expression %> can be used to evaluate an expression or call a server-side function. It’s also
used to display the value of variables and objects, as shown in the following code snippet from MSDN.
7|Page
The preceding code declares a function named GetTime. Note that this function could also be declared in the
code-behind file. The =GetTime() expression causes the function to be called, the current time evaluated.
The string is returned. That string is displayed in the output stream.

There is a special syntax that is used for binding expressions. As you will see, binding expressions are use with
ASP.NET controls to so as to “bind” them to a data source. For example, <%#
Eval(“fldSomething”) %>. Binding expressions will be covered in detail later as we begin to perform
more complex binding.

The final syntax variation is the one just used mostly for data source expressions rather than code. Here, we use
the <%$ %> syntax. Expressions are a declarative way to set control properties based on data that is not
evaluated until run-time. This way, you can set property values based on connection strings or application
settings.
Here we fully discuss the syntax of expressions. They always have the form:
<%$ expressionPrefix: expressionValue %>
Where the expressionPrefix contains the type of expression. AppSettings, ConnectionStrings, and
Resources are common ASP.NET expressions. And expressionvalue contains the expression that will be
resolved. Note that all of the functionality of expressions as hard-wired into the asp.net infrastructure. You do not
generally change the behavior of these expressions.
ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>"
The preceding fragment says to evaluate the ConnectionStrings expression using the value
ConnectionString2. Thus, the worker looks in the web.config file (this response is hardwired) for the
corresponding connection string and stores it in the corresponding SQLDataSource ConnectionString property.
The following snippet shows the corresponding entry in the web.config file:
8|Page
Lab Exercise 2 – Using the SqlDataSource to Display Data in a GridView
In this exercise, you will use the GridView control to display data from the SqlDataSource that you created
previously.
1. Make sure that Visual Studio is in design mode and that the form named Default.aspx is active.
2. Using the Toolbox, create a GridView control on the form. If you are using Source view, make sure that the
GridView declaration appears inside of the <form> block but not inside of the <asp:SqlDataSource>
declaration. If you are using Design view, draw the control after the SqlDataSource. Your code should be
similar to the following.
3. Next, you need to begin to configure the control. These configuration tasks can be performed using the
GridView tools or by directly editing the .aspx file. All the GridView configuration tool does is to edit .aspx
code.
4. While in the designer, click the GridView control to activate it. Again, an arrow should appear in the upperright region of the visible grid.
5. In the Choose Data Source drop-down, select the SqlDataSource that you created previously. This data
source should be named SqlDataSource1. Note that the following code was added by the Wizard to set the
DataSourceID of the GridView to the name of the SqlDataSource. This is all that is required to bind
9|Page
the GridView to a data source.
6. Run the program. The grid should be populated as follows:
7. End the program.
Next, you will enable editing on the control. The GridView has the ability to execute three “commands”



You can enable editing which allows the user select a row, edit it, and save the changes.
You can enable deletion, which allows the user to delete a row.
The can enable selection, which allows the user to select a row making it the current row. Selection is useful
when working with one-to-many relationships. When a row is selected in the master table, the corresponding
rows are displayed in a child table.
When you enable any of these three commands, The <asp:CommandField> tag is inserted inside of the
<Columns> tag as follows. The reason is simple, the CommandField is rendered as a column in the grid. The
following code snippet shows the GridView with the delete, edit, and select buttons enabled.
Note that the GridView does not support an Insert command. It’s possible to use the GridView to insert rows.
1. Run the program again. You will see Edit, Delete and Update buttons in the first column as the following figure
shows:
2. Click the Edit button for any of the rows. Change the last name as you see fit and then click the Update button.
THE FOLLOWING EXCEPTION IS THROWN BECAUSE THERE IS A BUG IN THE CODE GENERATOR THAT CREATED
THE UPDATE STATEMENT FOR YOU.
10 | P a g e
3. End the program.
4. Take close look at the UpdateCommand for the SqlDataSource.
5. In class, we discussed named parameters (with the @ sign). Access uses positional parameters. Each parameter
is marked with a question mark character. If you look at the code, you will see that there are 8 parameters.
However, if you look at the actual UpdateParameters, you will see that there are only 7. Modify the
UpdateCommand to remove the OR … IS NULL clause as follows. Thus, you are removing the extra parameter:
6. Run the program again. You should see that the edit is successful.
Lab Exercise 3 – Using the DataReader
The DataReader control is a one-way forward only reader that is used to read one record at a time from a data source. It
is very fast because we do not need the infrastructure to allow editing.
1. On the same form, create a button to display customers in a table using a data reader. In addition, create the
ASP Table control. You design code should look like the following:
11 | P a g e
2. Enter the following using statements so that the database libraries can be located:
3. Next, create the following code that will create an OleDbCommand object using information form the
SqlDataSource. This code assumes that the SqlDataSource is named SqlDataSource1.
4. Run the application. You will see the customer number appearing in the default page.
12 | P a g e
5. Extend the application and the code on this page to display the fields named fldFirstName and fldLastName in
the table cells.
Lab Exercise 4 –
In this lab exercise you will “go it on your own”.
1. Create a second form.
2. Create an SqlDataSource on the form so that you can get a reference to a connection as before. This time,
however, use the table named tblInvoices. Modify the SELECT statement by adding one parameter. This
parameter should contain the customer number. There are many invoices for each customer number.
3. Allow the user to enter a customer number in a text box (customer numbers vary from 1-3)
4. In a submit button, get the corresponding records and display them in a grid view. To help you, here is the data
binding code from last week.
13 | P a g e
Download