CHAPTER 9 Using the SqlDataSource Control The current movie category is added to the Session object in the Page_Load method.. Programmatically Executing SqlDataSource Commands You a
Trang 1CHAPTER 9 Using the SqlDataSource Control
<asp:DetailsView
id=”dtlMovie”
DataSourceID=”srcMovie”
Runat=”server” />
<asp:HyperLink
Runat=”server”
Text=”Back ”
NavigateUrl=”~/ShowQueryStringParameterMaster.aspx” />
<asp:SqlDataSource
id=”srcMovie”
SelectCommand=”SELECT * FROM Movies
WHERE Id=@Id”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
Runat=”server”>
<SelectParameters>
<asp:QueryStringParameter
Name=”Id”
QueryStringField=”Id” />
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
The SqlDataSource control in Listing 9.24 includes a QueryStringParameter The
QueryStringParameter supplies the movie ID in the SqlDataSource control’s
SelectCommand
Using the SessionParameter Object
The SessionParameter object enables you to represent any item stored in Session state
The SessionParameter object includes all the properties of the base Parameter class and
the following property:
SessionField—The name of the item stored in Session state that the
SessionParameter represents
NOTE
Session state is discussed in detail in Chapter 28
Trang 2The page in Listing 9.25 contains a GridView that displays a list of movies matching a
movie category The movie category is stored in Session state
LISTING 9.25 ShowSessionParameter.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
void Page_Load()
{
Session[“MovieCategoryName”] = “Animation”;
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show SessionParameter</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
Runat=”server” />
<asp:SqlDataSource
id=”srcMovies”
SelectCommand=”SELECT Name As Category,Title,Director
FROM Movies
INNER JOIN MovieCategories
ON CategoryId = MovieCategories.id
WHERE Name=@Name”
ConnectionString=”<%$ ConnectionStrings:Movies %>”
Runat=”server”>
<SelectParameters>
<asp:SessionParameter
Name=”Name”
SessionField=”MovieCategoryName” />
</SelectParameters>
</asp:SqlDataSource>
Trang 3CHAPTER 9 Using the SqlDataSource Control
</div>
</form>
</body>
</html>
The current movie category is added to the Session object in the Page_Load() method
The SqlDataSource reads the MovieCategoryName item from Session state when it
retrieves the list of movies that the GridView displays
Programmatically Executing SqlDataSource
Commands
You aren’t required to use the SqlDataSource control only when working with DataBound
controls You can create parameters and execute the commands represented by a
SqlDataSource control by working directly with the properties and methods of the
SqlDataSource control in your code
In this section, you learn how to add parameters programmatically to a SqlDataSource
control You also learn how to execute select, insert, update, and delete commands when
using the SqlDataSource control
Adding ADO.NET Parameters
Under the covers, the SqlDataSource control uses ADO.NET objects such as the ADO.NET
DataSet, DataReader, Parameter, and Command objects to interact with a database In
particular, any ASP.NET Parameter objects that you declare when working with the
SqlDataSource control get converted into ADO.NET Parameter objects
In some cases, you want to work directly with these ADO.NET Parameter objects when
using the SqlDataSource control For example, you might want to add additional
ADO.NET parameters programmatically before executing a command
The page in Listing 9.26 automatically adds an ADO.NET Parameter that represents the
current user’s username to the command that the SqlDataSource executes
LISTING 9.26 AddParameter.aspx
<%@ Page Language=”C#” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
protected void srcGuestBook_Inserting(object sender,
Trang 4{
e.Command.Parameters.Add(new SqlParameter(“@Name”, User.Identity.Name));
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show ProfileParameter</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:FormView
id=”frmGuestBook”
DataSourceID=”srcGuestBook”
DefaultMode=”Insert”
Runat=”server”>
<InsertItemTemplate>
<asp:Label
id=”lblComments”
Text=”Enter Your Comments:”
Runat=”server” />
<br />
<asp:TextBox
id=”txtComments”
Text=’<%# Bind(“Comments”) %>’
TextMode=”MultiLine”
Columns=”50”
Rows=”4”
Runat=”server” />
<br />
<asp:Button
id=”btnInsert”
Text=”Add Comments”
CommandName=”Insert”
Runat=”server” />
</InsertItemTemplate>
</asp:FormView>
<hr />
<asp:GridView
Trang 5CHAPTER 9 Using the SqlDataSource Control
id=”grdGuestBook”
DataSourceID=”srcGuestBook”
Runat=”server” />
<asp:SqlDataSource
id=”srcGuestBook”
SelectCommand=”SELECT Name,Comments,EntryDate
FROM GuestBook ORDER BY Id DESC”
InsertCommand=”INSERT GuestBook (Name,Comments)
VALUES (@Name,@Comments)”
ConnectionString=”<%$ ConnectionStrings:GuestBook %>”
Runat=”server” OnInserting=”srcGuestBook_Inserting” />
</div>
</form>
</body>
</html>
The page in Listing 9.26 includes a srcGuestBook_Inserting() event handler, which
executes immediately before the SqlDataSource control executes its insert command In
the event handler, a new ADO.NET Parameter is added to the insert command, which
represents the current user’s username
NOTE
The names of ADO.NET parameters, unlike ASP.NET parameters, always start with the
character @
Executing Insert, Update, and Delete Commands
The SqlDataSource control has methods that correspond to each of the different types of
commands that it represents:
Delete—Enables you to execute a SQL delete command
Insert—Enables you to execute a SQL insert command
Select—Enables you to execute a SQL select command
Update—Enables you to execute a SQL update command
For example, the page in Listing 9.27 contains a form for adding new entries to the
GuestBook database table This form is not contained in a DataBound control such as the
FormView or DetailsView controls The form is contained in the body of the page When
you click the Add Entry button, the SqlDataSource control’s Insert() method is
executed
Trang 6LISTING 9.27 ExecuteInsert.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<script runat=”server”>
/// <summary>
/// When button clicked, execute Insert command
/// </summary>
protected void btnAddEntry_Click(object sender, EventArgs e)
{
srcGuestBook.InsertParameters[“Name”].DefaultValue = txtName.Text;
srcGuestBook.InsertParameters[“Comments”].DefaultValue = txtComments.Text;
srcGuestBook.Insert();
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Execute Insert</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblName”
Text=”Name:”
AssociatedControlId=”txtName”
Runat=”server” />
<br />
<asp:TextBox
id=”txtName”
Runat=”server” />
<br /><br />
<asp:Label
id=”lblComments”
Text=”Comments:”
AssociatedControlId=”txtComments”
Runat=”server” />
<br />
<asp:TextBox
Trang 7CHAPTER 9 Using the SqlDataSource Control
id=”txtComments”
TextMode=”MultiLine”
Columns=”50”
Rows=”2”
Runat=”server” />
<br /><br />
<asp:Button
id=”btnAddEntry”
Text=”Add Entry”
Runat=”server” OnClick=”btnAddEntry_Click” />
<hr />
<asp:GridView
id=”grdGuestBook”
DataSourceId=”srcGuestBook”
Runat=”server” />
<asp:SqlDataSource
id=”srcGuestBook”
ConnectionString=”<%$ ConnectionStrings:GuestBook %>”
SelectCommand=”SELECT Name,Comments FROM GuestBook
ORDER BY Id DESC”
InsertCommand=”INSERT GuestBook (Name,Comments)
VALUES (@Name,@Comments)”
Runat=”server”>
<InsertParameters>
<asp:Parameter Name=”Name” />
<asp:Parameter Name=”Comments” />
</InsertParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Executing Select Commands
The procedure for executing a select command is different from executing insert,
update, and delete commands because a select command returns data This section
discusses how you can execute the SqlDataSource control’s Select() method
Trang 8Remember that a SqlDataSource control can return either a DataView or DataReader
depending on the value of its DataSourceMode property The SqlDataSource control’s
Select() method returns an object of type IEnumerable Both DataViews and DataReaders
implement the IEnumerable interface
To understand how you can call the Select() method programmatically, look at the
following simple photo gallery application This application enables you to upload images
to a database table and display them in a page (see Figure 9.14)
FIGURE 9.14 A photo gallery application
First, you need to create the page that displays the images and contains the form for
adding new images The PhotoGallery.aspx page is contained in Listing 9.28
LISTING 9.28 PhotoGallery.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Photo Gallery</title>
</head>
<body>
<form id=”form1” runat=”server”>
Trang 9CHAPTER 9 Using the SqlDataSource Control
<div>
<asp:DataList
id=”dlstImages”
DataSourceID=”srcImages”
RepeatColumns=”3”
Runat=”server”>
<ItemTemplate>
<asp:Image ID=”Image1”
ImageUrl=’<%# String.Format(“DynamicImage.ashx?id={0}”, Eval(“Id”)) %>’
Width=”250”
Runat=”server” />
<br />
<%# Eval(“Description”) %>
</ItemTemplate>
</asp:DataList>
<hr />
<asp:FormView
id=”frmImage”
DataSourceID=”srcImages”
DefaultMode=”Insert”
Runat=”server”>
<InsertItemTemplate>
<asp:Label
id=”lblImage”
Text=”Upload Image:”
AssociatedControlId=”upImage”
Runat=”server” />
<br />
<asp:FileUpload
id=”upImage”
FileBytes=’<%# Bind(“Image”) %>’
Runat=”server” />
<br /><br />
<asp:Label
id=”lblDescription”
Text=”Description:”
AssociatedControlID=”txtDescription”
Runat=”server” />
<br />
<asp:TextBox
Trang 10id=”txtDescription”
Text=’<%# Bind(“Description”) %>’
TextMode=”MultiLine”
Columns=”50”
Rows=”2”
Runat=”server” />
<br /><br />
<asp:Button
id=”btnInsert”
Text=”Add Image”
CommandName=”Insert”
Runat=”server” />
</InsertItemTemplate>
</asp:FormView>
<asp:SqlDataSource
id=”srcImages”
SelectCommand=”SELECT ID,Description FROM Images”
InsertCommand=”INSERT Images (Image,Description)
VALUES (@Image,@Description)”
ConnectionString=”<%$ ConnectionStrings:Images %>”
Runat=”server” />
</div>
</form>
</body>
</html>
The page in Listing 9.28 has a FormView control that contains a FileUpload control You
can use the FileUpload control to upload images from your local hard drive to the
appli-cation’s database table
Also, the page contains a DataList control that displays the image The Image control
contained in the DataList control’s ItemTemplate points to a file named
DynamicImage.ashx, which represents an HTTP Handler that renders a particular image
The DynamicImage.ashx handler is contained in Listing 9.29
NOTE
HTTP handlers are discussed in detail in Chapter 31, “Working with the HTTP Runtime.”