LISTING 18.31 FilterMovies.cs using System; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.Configuration; public class FilterMovies { private readonl
Trang 1CHAPTER 18 Using the ObjectDataSource Control
LISTING 18.30 ShowFilteredMovies.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>Show Filtered Movies</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:DropDownList
id=”ddlMovieCategory”
DataSourceID=”srcMovieCategories”
DataTextField=”Name”
DataValueField=”Id”
Runat=”server” />
<asp:Button
id=”btnSelect”
Text=”Select”
Runat=”server” />
<hr />
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
AutoGenerateColumns=”false”
Runat=”server”>
<Columns>
<asp:BoundField
DataField=”Title”
HeaderText=”Movie Title” />
<asp:BoundField
DataField=”Director”
HeaderText=”Movie Director” />
</Columns>
</asp:GridView>
<asp:ObjectDataSource
id=”srcMovieCategories”
TypeName=”FilterMovies”
SelectMethod=”GetMovieCategories”
Trang 2EnableCaching=”true”
CacheDuration=”Infinite”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”FilterMovies”
SelectMethod=”GetMovies”
EnableCaching=”true”
CacheDuration=”Infinite”
FilterExpression=”CategoryID={0}”
Runat=”server”>
<FilterParameters>
<asp:ControlParameter
Name=”Category”
ControlID=”ddlMovieCategory” />
</FilterParameters>
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
Both ObjectDataSource controls in Listing 18.30 have caching enabled Furthermore, the
second ObjectDataSource control includes a FilterExpression property that filters the
cached data, using the selected movie category from the DropDownList control
Both ObjectDataSource controls represent the component in Listing 18.31
LISTING 18.31 FilterMovies.cs
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class FilterMovies
{
private readonly string _conString;
public DataSet GetMovies()
Trang 3CHAPTER 18 Using the ObjectDataSource Control
SqlConnection con = new SqlConnection(_conString);
// Initialize DataAdapter
string commandText = “SELECT Title,Director,CategoryId FROM Movies”;
SqlDataAdapter dad = new SqlDataAdapter(commandText, con);
// Return DataSet
DataSet dstMovies = new DataSet();
using (con)
{
dad.Fill(dstMovies);
}
return dstMovies;
}
public DataSet GetMovieCategories()
{
// Initialize connection
SqlConnection con = new SqlConnection(_conString);
// Initialize DataAdapter
string commandText = “SELECT Id,Name FROM MovieCategories”;
SqlDataAdapter dad = new SqlDataAdapter(commandText, con);
// Return DataSet
DataSet dstCategories = new DataSet();
using (con)
{
dad.Fill(dstCategories);
}
return dstCategories;
}
public FilterMovies()
{
_conString =
➥WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString;
}
}
The ObjectDataSource enables you to filter data only when the data is represented by a
DataSet, DataTable, or DataView object This means that if you use filtering, the data must
be returned as one of these objects
Trang 4NOTE
Behind the scenes, the ObjectDataSource control uses the DataView.RowFilter
property to filter database rows You can find detailed documentation on proper filter
syntax by looking up the DataColumn.Expression property in the NET Framework SDK
Documentation
The ObjectDataSource control supports the following events:
Deleting—Occurs immediately before the method represented by the DeleteMethod
property is called
Deleted—Occurs immediately after the method represented by the DeleteMethod
property is called
Inserting—Occurs immediately before the method represented by the InsertMethod
property is called
Inserted—Occurs immediately after the method represented by the InsertMethod
property is called
Selecting—Occurs immediately before the method represented by the SelectMethod
property is called
Selected—Occurs immediately after the method represented by the InsertMethod
property is called
Updating—Occurs immediately before the method represented by the InsertMethod
property is called
Updated—Occurs immediately after the method represented by the InsertMethod
property is called
Filtering—Occurs immediately before the filter expression is evaluated
ObjectCreating—Occurs immediately before the object represented by the
ObjectDataSource control is created
ObjectCreated—Occurs immediately after the object represented by the
ObjectDataSource control is created
ObjectDisposing—Occurs before the object represented by the ObjectDataSource
control is destroyed
Most of these events come in pairs One event happens immediately before a method is
called, and one event happens immediately after a method is called You can handle these
Trang 5CHAPTER 18 Using the ObjectDataSource Control
You can also use these events to handle any errors that might result from calling methods
with the ObjectDataSource control
Adding and Modifying Parameters
You can handle the Selecting, Inserting, Updating, and Deleting events to modify the
parameters that are passed to the methods called by the ObjectDataSource control There
are several situations in which you might want to do this
First, if you work with an existing component, you might need to change the names of
the parameters passed to the component For example, instead of passing a parameter
named id to an update method, you might want to rename the parameter to movieId
Second, you might want to pass additional parameters to the method called For example,
you might need to pass the current username, the current IP address, or the current date
and time as a parameter to a method
For example, imagine that you want to create a guestbook and automatically associate the
IP address of the user making an entry with each entry in the guestbook The page in
Listing 18.32 illustrates how you can do this with the help of a FormView control and an
ObjectDataSource control (see Figure 18.9)
FIGURE 18.9 Displaying a guestbook
Trang 6LISTING 18.32 ShowGuestbook.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”>
protected void srcGuestbook_Inserting(object sender,
➥ObjectDataSourceMethodEventArgs e)
{
e.InputParameters.Add(“IPAddress”, Request.UserHostAddress);
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1” runat=”server”>
<style type=”text/css”>
.guestbook td,.guestbook th
{
padding:5px;
font:14px Arial,Sans-Serif;
}
</style>
<title>Show Guestbook</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:FormView
id=”frmGuestbook”
DataSourceID=”srcGuestbook”
DefaultMode=”Insert”
Runat=”server”>
<InsertItemTemplate>
<asp:Label
ID=”lblComment”
Text=”Comment:”
AssociatedControlID=”txtComment”
Runat=”server” />
<br />
<asp:TextBox
id=”txtComment”
Text=’<%# Bind(“comment”) %>’
TextMode=”MultiLine”
Trang 7CHAPTER 18 Using the ObjectDataSource Control
Runat=”server” />
<br />
<asp:Button
id=”btnInsert”
Text=”Add Entry”
CommandName=”Insert”
Runat=”server” />
</InsertItemTemplate>
</asp:FormView>
<hr />
<asp:GridView
id=”grdGuestbook”
DataSourceID=”srcGuestbook”
CssClass=”guestbook”
Runat=”server” />
<asp:ObjectDataSource
id=”srcGuestbook”
TypeName=”Guestbook”
SelectMethod=”GetEntries”
InsertMethod=”AddEntry”
OnInserting=”srcGuestbook_Inserting”
Runat=”server” />
</div>
</form>
</body>
</html>
The page in Listing 18.32 includes an Inserting event handler When the insert method is
called, the IP address of the current user is added to the parameters collection
The ObjectDataSource control in Listing 18.32 is bound to the Guestbook component in
Listing 18.33
LISTING 18.33 Guestbook.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class Guestbook
{
private string _conString;
Trang 8public SqlDataReader GetEntries()
{
// Initialize connection
SqlConnection con = new SqlConnection(_conString);
// Initialize command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “SELECT Id,IPAddress,Comment,EntryDate FROM Guestbook”;
// Execute command
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public void AddEntry(string IPAddress, string comment)
{
// Initialize connection
SqlConnection con = new SqlConnection(_conString);
// Initialize command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “INSERT Guestbook (IPAddress,Comment)” +
“ VALUES (@IPAddress, @Comment)”;
// Add ADO.NET parameters
cmd.Parameters.AddWithValue(“@IPAddress”, IPAddress);
cmd.Parameters.AddWithValue(“@Comment”, comment);
// Execute command
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
public Guestbook()
{
_conString =
➥WebConfigurationManager.ConnectionStrings[“Guestbook”].ConnectionString;
}
Trang 9CHAPTER 18 Using the ObjectDataSource Control
Realize that you can manipulate the parameters collection in any way that you need You
can change the names, types, or values of any of the parameters
Handling Method Errors
You can handle the Selected, Inserted, Updated, or Deleted events to handle any errors
that might result from calling a method For example, the page in Listing 18.34 handles
the Inserting event to capture any errors raised when the method represented by the
ObjectDataSource control’s InsertMethod property is called
LISTING 18.34 HandleErrors.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”>
protected void srcMovies_Inserted(object sender,
➥ObjectDataSourceStatusEventArgs e)
{
if (e.Exception != null)
{
e.ExceptionHandled = true;
lblError.Text = “Could not insert movie”;
}
}
</script>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
}
.insertForm
{
background-color:white;
}
.insertForm td,.insertForm th
{
padding:10px;
}
.error
{
color:red;
Trang 10font:bold 14px Arial,Sans-Serif;
}
</style>
<title>Handle Errors</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblError”
EnableViewState=”false”
CssClass=”error”
Runat=”server” />
<h1>Insert Movie</h1>
<asp:DetailsView
id=”dtlMovies”
DataSourceID=”srcMovies”
DefaultMode=”Insert”
AutoGenerateInsertButton=”true”
AutoGenerateRows=”false”
CssClass=”insertForm”
GridLines=”None”
Runat=”server”>
<Fields>
<asp:BoundField
DataField=”Title”
HeaderText=”Title:”/>
<asp:BoundField
DataField=”Director”
HeaderText=”Director:” />
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”InsertMovie”
InsertMethod=”Insert”
Runat=”server” OnInserted=”srcMovies_Inserted” />
</div>
</form>
</body>