Creating an SQL Server Database

advertisement
IS 460
ASP.NET Lab (Database Introduction)
Ekedahl
In this lab, you will perform the following:






Create a connection to SQL Server and create database tables
Create an SqlDataSource that uses the above connection
Create a simple GridView using default properties
Create a GridView with custom columns
Create two synchronized GridView controls using a master-detail (one-to-many) relationship.
Create a bound DropDownList from which the user can select bound data items
In this lab, you will create a local database for development. You will use the SqlCommand,
DataAdapter, and the other objects we have discussed to programmatically work with a single-table
database.
Creating an SQL Server Database
For all of the database labs in this course, you will work with the same SQL server that you use(d) in IS
475. The following tutorial
HANDS ON EXERCISE: Connecting to SQL Server and populating a Database
In this first exercise, you will use SQL Server Management Studio to create tables in a database that has
already been created for you. On campus, all of the software is available in the COBA labs. From home,
you can also work on the student terminal server, which is available via a remote desktop session. I do
not spend much time in this lab discussing how to use Remote Desktop or how to use SQL Server
Management Studio. All of these tasks should be familiar to you from IS 475.
1. Start SQL Server Management Studio either on a lab computer or on the student terminal
server (sts.coba.unr.edu). I assume that you know how to create a remote desktop session to
sts.coba.unr.edu.
2. In the Connect to Server dialog that follows, make sure the server name is set to
ISSQL\STUDENTS. Make sure to use Windows Authentication. Your user name should already
be filled in, along with your NETID.
1|Page
Click Connect to connect to the database server. The database on the server appears in the
Databases folder. For this course, use the database named 460 followed by your NETID. DO
NOT USE THE DATABASE FOR IS 475 OR IS 485! Your databases appear in the Object Explorer as
shown in the following figure. If the Object Explorer is not visible, click View, Object Explorer on
the menu: Note, this is what I see in the Object Explorer. You might see different databases
because I have different rights to the server than you do.
3. Run the following scripts to create the two tables used in this lab or create the tables as follows.
You can also use the table designer in SQL Server Management Studio.
2|Page
Note that the field named fldCustomerID in the table tblCustomer and the field name fldTransactionID
in the table tblTransaction are identify fields. If you have not created one, select the column and edit the
following property.
3|Page
USE [CHANGETODATABASENAME]
GO
/****** Object: Table [dbo].[tblCustomer]
SET ANSI_NULLS ON
GO
Script Date: 10/14/2015 9:54:12 AM ******/
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblCustomer](
[fldCustomerID] [int] IDENTITY(1,1) NOT NULL,
[fldLastName] [varchar](50) NOT NULL,
[fldFirstName] [varchar](50) NOT NULL,
[fldBalance] [float] NOT NULL,
[fldLastAccess] [date] NOT NULL,
[fldActive] [bit] NOT NULL,
CONSTRAINT [PK_tblCustomer] PRIMARY KEY CLUSTERED
(
[fldCustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblTransactions](
[fldTransactionID] [int] IDENTITY(1,1) NOT NULL,
[fldCustomerID] [int] NOT NULL,
[fldTransactionType] [varchar](10) NOT NULL,
[fldTransactionAmount] [float] NOT NULL,
CONSTRAINT [PK_tblTransactions] PRIMARY KEY CLUSTERED
(
[fldTransactionID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
4|Page
Populate the tables with two or three rows similar to the following:
Creating a SQL Server Connection in a Visual Studio Web Site
HANDS ON EXERCISE: – Creating the Web site
In this exercise you will connect to the tables that you created in the previous exercise.
1. Make sure that you are using Visual Studio 2013. There are several Visual Studio versions
installed on the sts terminal server.
2. Create a new empty Web site as you have been doing. If you are using the student terminal
server, I suggest that you create the Web Site in the folder C:\users\netid where netid is your
actual NETID. Note that VB is selected as the default programming language in the labs and
the sts terminal server.
MAKE SURE TO CLICK THE Visual C# TEMPLATE AN NOT THE Visual Basic TEMPLATE!!!
5|Page
3. Create a Web form named Default.aspx.
HANDS ON EXERCISE: Creating a Connection String
In this part of the lab, you will create a global connection string that will (can) be used by the
application’s other Web Forms, because the connection string is stored in the application’s web.config
file.
This is the same connection string that we discussed in class. There are a couple of different ways to
accomplish this task:

You could manually create the connection string in the Web.config file.

You could use the SqlDataSource control to create the connection string for you. There is no
Wizard that I know of that just creates the connection string.
In this exercise, you will use the SqlDataSource control.
1. Make sure that the page named Default.aspx is active.
2. Open the toolbox so that the controls are visible. Expand the Data tab so that you can see the
SqlDataSource control as shown in the following figure:
6|Page
3. If you are in design mode, drag the SqlDataSource control from the ToolBox to the visual
form surface. You should see the control on the design surface as follows:
4. If you are in source mode, drag the SqlDataSource control so that it appears inside of the
<form> tag. You should see the following code written by the Wizard:
Whether you created the SqlDataSource control in the source window or on the design
surface, the same code is generated in the .aspx file.
Next, you will begin to configure the control instance.
1. Make sure that the form is in Design view, and that the SqlDataSource control is visible in
form’s visible region.
7|Page
2. Along the right side of the control, an arrow appears. Click the arrow and then click the link
titled Configure Data Source…
3. The following dialog box appears:
4. Click the New Connection button. You will be connecting to SQL server. The following dialog box
may or may not appear depending on your user profile. If it does, select Microsoft SQL Server.
8|Page
5. Click Continue to display the Add Connection dialog box as shown in the following figure:
6. Select the Server named ISSQL\STUDENTS in the Server name drop-down box. This may take a
minute because the system is looking for all of the available SQL Server connections on the
network. If this server name does not appear, click the Refresh button. Make sure the radio
button titled Use Windows Authentication is selected.
7. Finally, in the Connect to a database section, select your database. Again use the database
named 460netid where netid is your netid. Note that my database is named ekedahl.
8. Click the Test Connection button at the bottom of the dialog box. You should see the following
message indicating that the connection test was successful.
9|Page
9. Click OK to close the dialog box.
10. At this point, the connection should have been created. If you expand the connection string
section, you will see the actual connection string. A connection string is made up of key/value
pairs separated by a semicolon:
The Data Source property points to the server (ISSQL)
The Initial Catalog key points to the database name (ekedahl).
Integrated Security = true indicates that you are using Windows Authentication. We will discuss
SQL Server authentication later in the course.
11. Click the Next button to begin configuring the SqlDataSource and to display the following
dialog box:
10 | P a g e
12. Make sure that the check box titled Yes, save this connection as: is is checked. Checking this
box causes the connection string to be written into the web.config file. If the box is not checked,
the connection string will be stored directly in the ConnectionString property of the
SqlDataSource.
Change the name of the connection string to LabConnectionString. As you will see in a
moment, this is the connection string that will be written to the web.config file. Click Next to
display the dialog in which you will configure the data source.
13. In the next steps, you will configure the SqlDataSource control itself. In this first example,
you will configure the SqlDataSource to select all records from the table named
tblCustomer. In subsequent exercises, you will create additional data sources that will perform
adds, changes, and deletes and create multiple data sources to work with multiple tables.
Select all of the fields from the table named tblCustomer as shown in the following figure. I
suggest that you select each field name individually.
11 | P a g e
Note that you can select any table from the database using the drop-down box. Note that as you
check the various fields, the SQL SELECT statement is shown in the multi-line text box at the
bottom of the dialog.
14. Click Next to display the following dialog box. Click the Test Query button to make sure that
things are working. You should see the two rows that were previously entered displayed in the
dialog box.
15. Click Finish.
12 | P a g e
HANDS ON EXERCISE: – Looking at What the Wizard Did
In this set up steps, you will look at all of the code generated by the Wizard. Note that you could have
just as well written all of this code yourself.
1. Open the Web.config file. You should see that the Wizard created the connection string as
follows:
The connection strings appear in the <connectionStrings> element. It’s possible to have
several connection strings in this section so the application can operate with multiple databases.
The name attribute defines the name by which the connection string can be programmatically
accessed. The connectionString property contains the actual connection string discussed
previously. Finally, the providerName attribute tells the run time to use the SQL Server
provider to access the database.
Now look at the Default.aspx file while in source mode. You should see that the
SqlDataSource is configured. The ConnectionString attribute is set to the
connectionsString stored in the Web.cofing file. The syntax might be a bit unclear. The
<%$ %> syntax is called a binding expression. It’s tells the run time to use the
LabConnectionString from the Web.config file. The SelectCommand attribute contains the
SELECT statement. Note that I have changed the formatting. The Wizard puts all the code on a
single line.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LabConnectionString %>"
SelectCommand="SELECT [fldCustomerID], [fldLastName], [fldFirstName],
[fldBalance], [fldLastAccess], [fldActive] FROM [tblCustomer]">
</asp:SqlDataSource>
Creating and Binding a GridView Control
You will work with the GridView control quite a bit in this lab. For this first example, you will create
the GridView and bind it to the SqlDataSource that you just created. There are a couple of ways
to do this. You can used the Tools and Wizard, which you will do in this exercise. You can also write the
code by hand in the .aspx file.
13 | P a g e
HANDS ON EXERCISE: – Creating and Binding a GridView control
1. Make sure the form named Default.aspx is active and in Design mode.
2. Create a GridView control instance on the form below the SqlDataSource control you just
created. To create the control instance, drag the control from the Toolbox on to the form’s
visual surface.
When you do, the screen should look like the following. In the Choose Data Source section,
select the SqlDataSource that you created previously. By default it is named
SqlDataSource1. If the GridView Tasks drop-down box does not appear, click the Open arrow
3. Switch to Source view. You should see the declarative code for the GridView. The only
required configuration option is to set the DataSourceID attribute to the SqlDataSource
instance. That one configuration entry is all that is needed to bind the GridView to the data
source.
4. Run the program. You should see the data appear in the Web browser as follows:
14 | P a g e
The GridView control supports many more properties than are shown in the visible control. These
properties and child elements are described in the following list.

The property named AutoGenerateColumns, when set to True, causes the GridView to
render all of the columns in bound data source. The column (field name) appears in the column
header. The data type of the rendered column is derived from the data type of the underlying
column (field). As this is the default value, the GridView will get the column names and data
from the bound data source.
If the property is set to False, then you must explicitly declare (specify) which columns to
render and in which order.

If the AutoGenerateColumns property is false, then the GridView control will have a
child <Columns> element. Each child element of <Columns> is used to describe column and
its binding to a field in the corresponding data source.

The DataKeyNames property should be set to the primary key field in the data source. It is
commonly used to get the primary key of the selected row. The value is accessed through the
SelectedDataKey property at run time.
Configuring the GridView to Display Custom Columns
In this exercise, you will you will continue to configure the GridView so that instead of displaying
default columns, you will display custom columns. In the tasks that follow, you will use the Wizard to do
most of the work. However, all of the code created by the Wizard could be written by hand in the .aspx
file. So as you work through these exercises, you will carefully examine the Wizard-generated code.
HANDS ON EXERCISE: – Configuring the GridView for manual column creation
By default, the GridView will generate columns based on those found in the bound data source. By
turning off automatic column generation, you have much more control over how each column is
rendered.
15 | P a g e
1. Make sure that the Designer is active for the Default.aspx form with which you have been
working. Select the GridView control instance. Click the right arrow to display the following
selection menu. Your screen should look like the following:
2. Click the Edit Columns menu item to display the following dialog box:
3. Uncheck the box titled Auto-generate fields.
If you were to run the program at this point. You would find that the grid would display nothing
because there is no data to be rendered. When the grid has no data to render, nothing appears.
Even the header row is hidden.
4. Click the Refresh Schema link. The Available fields section in the upper-left corner of the dialog
is updated. Collapse and scroll through the various field types. As you do, note the following
16 | P a g e
about these field (column) types:

A BoundField is the default column type. It displays the value of a field in a data source.

A ButtonField display a command button. You can create event handlers for these buttons.

A CheckBoxField renders a check box in each column. It is typically bound to a Boolean (bit)
field in the data source.

A CommandField is a restricted form of ButtonField. It has predefined buttons to select,
edit, and delete records.

A HyperLinkField works the same way as a ButtonField. However, the button appears
as a hyperlink.

An ImageField renders an image.

The TemplateField, discussed later, allows you to completely customize the appearance of
a column.
As you progress through this lab, you will work with most of these field (column) types.
5. At this point in the exercise, the Fields dialog should be displayed. However, there should not be
any fields selected. Next, you will see how to create a first BoundField by hand. Then, you
will explore the code generated by the Wizard.
In the Available field list box, expand the BoundField section. Select the field named
fldLastName, and click the Add button. The field should be added to the SelectedFields list box.
17 | P a g e
6. Scroll through the BoundField properties until you see the Data section. Note that the
DataField property is set to fldLastName. This is the name of field from the data source to
which the column is bound. Set the HeaderText property to Last Name as shown in the
above figure.
7. Click OK to close the dialog box.
8. The Designer will now show the BoundField in the visible region as follows:
9. Run the program. You should see the two rows from the column named fldLastName.
18 | P a g e
10. End the program.
11. View the Source window to see the code that was automatically generated.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="fldLastName" HeaderText="Last Name"
SortExpression="fldLastName" />
</Columns>
</asp:GridView>
When the AutoGenerateColumns property is false, you must declaratively create each of the
columns. Each column that you create appears as child element of the <Columns> element.




In the above, we create an <asp:BoundField>
The DataField=”fldLastName” binds the column to the field in the data source. If the
field name does not match a field in the data source, an exception will be thrown.
The HeaderText=”Last Name” attribute configures the text that appears in the column
header.
The SortExpression=”fldLastName” attribute controls column sorting and will be
discussed later.
Note that the order of the BoundField elements in the <Columns> collection is significant. Columns
are rendered in the order they appear in the <Columns> collection.
Next, you will continue to configure the remainder of the bound fields.
1. Activate the Fields dialog box again for the GridView.
2. Add the BoundField named fldFirstName. Change the HeaderText property to First Name.
3. Add the BoundField named fldBalance. Change the HeaderText property to Balance.
4. In the Available fields section, expand the CheckBoxField named fldActive. Add that field.
Be sure not to use a BoundField.
19 | P a g e
5. Click OK to close the dialog box. The GridView in Design mode should now appear as follows:
6. View the following declarative code was generated n the .aspx file by the Wizard:.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="fldLastName"
HeaderText="Last Name" SortExpression="fldLastName" />
<asp:BoundField DataField="fldFirstName"
HeaderText="First Name" SortExpression="fldFirstName" />
<asp:BoundField DataField="fldBalance"
HeaderText="Balance" SortExpression="fldBalance" />
<asp:CheckBoxField DataField="fldActive"
HeaderText="Active" SortExpression="fldActive" />
</Columns>
</asp:GridView>
Note that the above code:

The <Columns> collection appears as an immediate child of the GridView.

Each column that will be rendered appears as a child of the <Columns> element (collection).

The three BoundField columns will be rendered in order.
o
They will be bound to the corresponding field in the DataSource. Based on the
setting of the DataField property.
o
The HeaderText attribute defines the text that will appear in the header row.
o
The SortExpression property will be discussed in a moment.
20 | P a g e

The CheckBoxField will be rendered in the last column.
7. Now run the page. You should see the GridView displaying the following columns:
EXPLORATION EXERCISE: – Creating and Binding a GridView control
Now it’s your turn to configure an SqlDataSource and corresponding GridView. In this exercise,
you will create and SqlDataSource, configure it to display records from the table named
tblTransactions, and then create a GridView to display those records.
1. Create a new Web form named Transactions.aspx.
2. Create an SqlDataSource control on the form as you did before. Configure the
DataSource. Instead of creating a new connection, use the existing connection. It should
appear in the drop down box as follows:
3. This time, instead of selecting all rows from the table named tblCustomers, select all rows from
the table tblTransactions. When complete, you should end up with the following
SqlDataSource and declaration.
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LabConnectionString %>"
SelectCommand="SELECT [fldTransactionID], [fldCustomerID],
[fldTransactionType], [fldTransactionAmount] FROM [tblTransactions]">
</asp:SqlDataSource>
</form>
</body>
21 | P a g e
Note that this data source has nothing to do with the data source you created on the Default.aspx page.
Data sources are not shared across pages.
1. Create a GridView on the form.
2. Set the data source to SqlDataSource1. This is the data source that you just created on this
web form. It has nothing to do with the data source that you created on the previous page.
3. Select all columns except for the column named fldTransactionID. Set the column
headers such that the string fld is removed from the header text name.
4. Run the page in the browser. You should see the data from the table named tblTransactions
appear.
Working with Selection
So far, you have created an SqlDataSource and used it to connect a GridView to a table, and
display columnar data. But in any database application master / detail records need to be rendered. In
this section you will see how to select a master record in a GridView and display the corresponding
transactional records. To do this you will enhance the Default.aspx form that you have already created
to display the transactional table.
To do so, the following tasks need to be performed for the two SqlDataSource and GridView controls.

The first SqlDataSource need not be changed. It selects all rows from the table tblCustomer.

A second SqlDataSource need to be created on the page to select rows from the table
named tblCustomer. However, this second data source will use a parameter to select, in the
second grid, only those rows that match the selected customer in the first grid.

A second GridView control needs to be created. Again,
22 | P a g e
HANDS-ON EXERCISE: Creating an SqlDataSource with a parameter:
1. Make sure that the form named Default.aspx is active and in design mode.
2. Create a second instance of the SqlDataSource control on the form. Use the
LabConnectionString that you have been using.
3. Select all of the fields from the table named tblTransaction.
4. Click the Where… button to build a WHERE clause for the SELECT statement. The WHERE clause
you create will use a parameter to select only those customer records matching the selected
customer in the first GridView.
The Add WHERE Clause dialog box allows you to build a simple WHERE clause. The Column
Drop-down box allows you to select a column that will be used in the WHERE clause. The
Operator drop-down box allows you to select an SQL comparison operator (=, >, <, etc…). The
Source column does not really map to SQL as you know it.
If you set the Source property to Control the run time will fill in the parameter value based
on the value of another control. In this example, you will bind the parameter to the GridView
named GridView1 (the customer GridView). The property is actually bound to the
23 | P a g e
SelectedValue property of the first GridView, but this happens internally.
5. Complete the Add Where Clause dialog box as shown in the following figure:
6. Click the Add button so that the SQL expression appears in the Where Clause section as follows:
7. Click OK to close the dialog box. In the Configure Data Source dialog box, click Next and then
click Finish.
24 | P a g e
Take a close look at the declarative code generated by the Wizard:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:LabConnectionString %>"
SelectCommand="SELECT [fldTransactionID], [fldCustomerID],
[fldTransactionType],
[fldTransactionAmount] FROM [tblTransactions]
WHERE ([fldCustomerID] = @fldCustomerID)">
<SelectParameters>
<asp:ControlParameter ControlID="GridView1" Name="fldCustomerID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource

The ConnectionString property has the same value as before.

Note the addition of the WHERE clause. It is a parameterized WHERE clause. Rows are selected
where the field [fldCustomerID] is equal to the named parameter @fldCustomerID. Named
parameters always begin with the @ character.

When an SQL DataSource has parameters, the SqlDataSource element has a child
element named <SelectParameters>. There should be one parameter for each parameter
in the SELECT statement. Parameters can be of different types. In this case, the parameter is a
<ControlParameter> having the following attributes.
o
o
o
o
The ControlID property contain the name of the control to which the parameter is
bound. (In this case the GridView named GridView1).
The Name property contains the parameter name. The parameter name (fldCustomerID)
must match the parameter name in the SELECT statement (@fldCustomerID). Note that
the @ sign is removed from the parameter name.
The property name contains the name of the control property that will be bound. In this
case we are binding the SelectedValue of the GridView control.
The data Type of the property is an integer (Int32)
HANDS-ON EXERCISE: Modifying the Customer GridView to define a primary key:
In these next steps, you will enhance the first GridView control instance as follows:

The GridView control supports a property named DataKeyNames. When used, it should
contain the primary key of the column in underlying database table. The DataKeyNames
property is required so that the SelectedValue property of the grid will return the primary
key of the selected record.

So far, you have used the BoundField to element to bind a field. In this section, you will
create a button that will appear in each row. This button will select the current row. When
selected, the corresponding row will be selected in the 2nd grid.
25 | P a g e
1. Activate the Source window for the form named Default.aspx. Add the following attribute to the
GridView declaration: DataKeyNames="fldCustomerID" so that declaration matches the
following:
2. Next, you need to add the CommandField to the grid. As mentioned before, the
CommandField is rendered as a selectable button. The value of the HeaderText property
appears in the column header. A CommandField can render multiple buttons. Corresponding
button will be rendered if the ShowEditButton, ShowInsertButton,
ShowSelectButton properties are set to true. Add the following CommandField to the
GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames="fldCustomerID">
<Columns>
<asp:CommandField HeaderText="Select Record"
ShowSelectButton="True" SelectText="Detail" />
<asp:BoundField DataField="fldLastName"
HeaderText="Last Name" SortExpression="fldLastName" />
<asp:BoundField DataField="fldFirstName"
HeaderText="First Name" SortExpression="fldFirstName" />
<asp:BoundField DataField="fldBalance"
HeaderText="Balance" SortExpression="fldBalance" />
<asp:CheckBoxField DataField="fldActive"
HeaderText="Active" SortExpression="fldActive" />
</Columns>
</asp:GridView>
3. Run the program. You should see the CommandField appear in the first column of the grid. It
appears as link. The caption is Detail because you set the SelectText property to the string
Detail. If you click on the link at this point, nothing will happen because you have not yet
created or bound the second GridView control.
4. Next, create a second GridView control below the first.
5. Bind this 2nd GridView to the SqlDataSource named SqlDataSource2 (this is the 2nd data source
that you created.
6. Edit the columns. That is activate the Fields dialog box as you have done before.
26 | P a g e
7. Refresh the schema. When you do, the following dialog will appear asking you to complete the
value for the parameterized query. Enter 1 for the value and click OK.
8. Remove the Auto-generate fields check box. Select the BoundFields named fldTransactionID,
fldCustomerID, fldTransactionType, and fldTransactionAmount. The Fields dialog box should
resemble the following:
9. Run the program again. If you have configured the controls correctly, the transaction records
applicable to the selected customer will appear when you select a customer master record.
27 | P a g e
Performing Updates and Deletes
Suppose that you wanted the user to be able to update and delete the transactional records (in place).
That is, you want the user to update a row in a GridView. To accomplish this task, you need to make
modifications to the SqlDataSource, so that will support updates and deletes. You also need to
modify the GridView accordingly so that it will support and Edit and Delete button.
HANDS-ON EXERCISE. Supporting Updates and Deletes in a SqlDataSource.
1. Activate the form named Transactions.aspx. Make sure that the form is in Design mode.
2. Activate the SqlDataSource control on the page. Here, you are going to reconfigure the data
source so that it will perform updates and deletes. Click the Configure Data Source… Menu
item. Click Next to continue to use the same connection. The Configure Data Source Dialog
should appear. Click the Advanced button to display the following dialog box:
3. Click the Generate INSERT, UPDATE, and DELETE statements button. Do not use optimistic
concurrency. Click OK to return the Configure Data Source dialog box.
28 | P a g e
4. Click Finish to regenerate the code for the SqlDataSource.
Note the SqlDataSource code is updated as follows:
As discussed in class:

In addition to the SelectCommand, SQL statements are generated for the InsertCommand,
UpdateCommand, and DeleteCommand attributes. All use parametrized statements.

The DeleteParameters, InsertParameters, and UpdateParameters are
automatically generated.

The number and names of the parameters (in the InsertCommand, UpdateCommand, and
DeleteCommand), must match the actual parameters themselves.
HANDS-ON EXERCISE. Supporting Updates and Deletes in a GridView.
Next, you need to configure the GridView control instance to enable edits and deletes. You will not
enable record insertion. While it is possible to insert records with the GridView control, the process is
tricky. Ordinarily, we will use a FormView control for record insertion.
29 | P a g e
1. On the form named Transactions.aspx, select the GridView control while in Design view.
2. Click the right-arrow in the visible region to display the content (pop-up menu). Check the
Enable Editing and Enable Deleting button as shown in the following figure.
3. Add the field named fldTransactionID to the control instance. This field is required since you
need it to update the record based on the primary key.
4. When you do this, the following buttons appear in the first column of the grid.
5. Open the Transactions.aspx file in Source mode and make sure that the DataKeyNames property
is defined. Without, there is no primary key assigned an the update / deletes will not work
correctly. datakeynames="fldTransactionID"
6. Note that the following code was generated by the wizard
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
The above code is nearly as the code to display a Select button.
7. Run the application. Click the Edit button. The fields in the current row are editable. Change the
transaction type and the transaction amount. Enter valid data and click the Update button to
record the changes.
8. End the program.
Using a Bound DropDownList
Another common metaphor used when working with one-to-many relationships so to select an item in a
drop-down list. Then, we can display all of the detail information for the selected record. Or we can
30 | P a g e
display the record from the many table in a one-to-many relationship. In this exercise, you will perform
the latter.
1. Create a new Web Form named List.aspx. Create an SqlDataSource on the form. This
SqlDataSource will be used to select two fields from the table named tblCustomer. Use the
same connection string that you have been using (LabConnectionString).
2. This time, instead of having the Wizard create the SQL statement, you will need to create your
own. In the Configure Data Source dialog box, select the Specify a custom SQL statement or
stored procedure Radio Button as follows:
3. Click Next and enter the following SQL statement. There is a Query Builder that will help you
write the statement but it’s somewhat primitive. Note that you can also use this tool to create
custom INSERT, UPDATE, and DELETE statements but will not do so here.
4. Click Next, and then click Finish in the following dialog box to create the query. The following
code is generated.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LabConnectionString %>"
31 | P a g e
SelectCommand="SELECT fldCustomerID, fldLastName + ' ' + fldFirstName
AS fldFullName FROM tblCustomer">
</asp:SqlDataSource>
Next you will create a bound DropDownList. When you create a bound DropDownList, you are
usually interested in two properties.
HANDS-ON ACTIVITY: To create a bound DropDownList
1. Make sure the form named List.aspx is active and is visible in Design mode.
2. Create a DropDownList control on the form just below the SqlDataSource that you just
created.
3. Click Choose Data Source to display the following dialog box. Select the SqlDataSource named
SqlDataSource1. Click the Refresh Schema link Select the fields as follows:

The field named fldFullName will be rendered in the visible region of the control instance. (the
DataTextField property)

The field named fldCustomerID is called the data value. It contains the primary key of the
record. (the DataValueField property)
4. Click OK to close the dialog box. Make sure to enable AutoPostBack as follows:
32 | P a g e
5. Again, the following code is generated.
<asp:DropDownList ID="DropDownList1" runat="server"
autopostback="true"
DataSourceID="SqlDataSource1"
DataTextField="fldFullName"
DataValueField="fldCustomerID">
</asp:DropDownList>
1. Run the program. The bound data item should appear in the drop down list.
Next, you will create a second grid view on this form. However, you will bind it to the DropDownList.
Again, all of this can be accomplished declaratively.
1. On the form named Lists.aspx, create an SqlDataSource control instance that will select
records from the table tblTransactions. This SqlDataSource should use a
ControlParameter too. However, the ControlID will be the DropDownList and the
PropertyName will be SelectedValue (the selected value of the dropdown list configured
previously. The declarative code should look like the following.
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:LabConnectionString %>"
SelectCommand="SELECT [fldTransactionID], [fldCustomerID],
[fldTransactionType],
[fldTransactionAmount] FROM [tblTransactions] WHERE
([fldCustomerID] = @fldCustomerID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="fldCustomerID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
33 | P a g e
2. Now create the GridView control instance. This control instance is configured exactly the same
as the transaction GridView on the form named Default.aspx.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="fldTransactionID" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="fldTransactionID"
HeaderText="fldTransactionID"
InsertVisible="False" ReadOnly="True"
SortExpression="fldTransactionID" />
<asp:BoundField DataField="fldCustomerID" HeaderText="fldCustomerID"
SortExpression="fldCustomerID" />
<asp:BoundField DataField="fldTransactionType"
HeaderText="fldTransactionType"
SortExpression="fldTransactionType" />
<asp:BoundField DataField="fldTransactionAmount"
HeaderText="fldTransactionAmount"
SortExpression="fldTransactionAmount" />
</Columns>
</asp:GridView>
3. Run the program. Select an item from the drop-down list. The corresponding transactions
should appear in the grid.
34 | P a g e
Download