public void UpdateMovieint id, string title, string director, DateTime ➥dateReleased { // Create Command SqlConnection con = new SqlConnection_conString; SqlCommand cmd = new SqlCommand;
Trang 1public void UpdateMovie(int id, string title, string director, DateTime
➥dateReleased)
{
// Create Command
SqlConnection con = new SqlConnection(_conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “UPDATE Movies SET
Title=@Title,Director=@Director,DateReleased=
// Add parameters
cmd.Parameters.AddWithValue(“@Title”, title);
cmd.Parameters.AddWithValue(“@Director”, director);
cmd.Parameters.AddWithValue(“@DateReleased”, dateReleased);
cmd.Parameters.AddWithValue(“@Id”, id);
// Execute command
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
public SqlDataReader GetMovies()
{
// Create Connection
SqlConnection con = new SqlConnection(_conString);
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “SELECT Id,Title,Director,DateReleased FROM Movies”;
// Return DataReader
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public Movies()
{
_conString =
WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString;
}
}
Trang 2The page in Listing 18.12 contains a GridView and ObjectDataSource control The
ObjectDataSource control includes an UpdateMethod property that points to the
UpdateMovie() method
LISTING 18.12 ShowMovies.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 Movies</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
DataKeyNames=”Id”
AutoGenerateEditButton=”true”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”Movies”
SelectMethod=”GetMovies”
UpdateMethod=”UpdateMovie”
Runat=”server”/>
</div>
</form>
</body>
</html>
In Listing 18.12, the GridView automatically adds the update parameters to the
ObjectDataSource control’s UpdateParameters collection As an alternative, you can
declare the parameters used by the ObjectDataSource control explicitly For example, the
page in Listing 18.13 declares all the parameters passed to the UpdateMovie() method
LISTING 18.13 ExplicitShowMovies.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
Trang 3<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show Movies</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
DataKeyNames=”Id”
AutoGenerateEditButton=”true”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”Movies”
SelectMethod=”GetMovies”
UpdateMethod=”UpdateMovie”
Runat=”server”>
<UpdateParameters>
<asp:Parameter Name=”title” />
<asp:Parameter Name=”director” />
<asp:Parameter Name=”dateReleased” Type=”DateTime” />
<asp:Parameter Name=”id” Type=”Int32” />
</UpdateParameters>
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
The ObjectDataSource uses reflection to match its parameters against the parameters of
the method that it calls The order of the parameters does not matter, and the case of the
parameters does not matter However, the one thing that does matter is the names of the
parameters
You specify the type of a parameter with the Type property, which represents a member of
the TypeCode enumeration The TypeCode enumeration represents an enumeration of
common NET Framework data types such as Int32, Decimal, and DateTime If the
enumeration does not include a data type that you need, you can use the
TypeCode.Object member from the enumeration
Trang 4Using Different Parameter Types
You can use all the same types of parameters with the ObjectDataSource control that you
can use with the SqlDataSource control:
Parameter—Represents an arbitrary static value
ControlParameter—Represents the value of a control or page property
CookieParameter—Represents the value of a browser cookie
FormParameter—Represents the value of an HTML form field
ProfileParameter—Represents the value of a Profile property
QueryStringParameter—Represents the value of a query string field
SessionParameter—Represents the value of an item stored in Session state
For example, the page in Listing 18.14 contains a DropDownList control and a GridView
control, which enables you to view movies that match a selected category (see Figure 18.3)
FIGURE 18.3 Displaying movies by category
LISTING 18.14 ShowMoviesByCategory.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” >
Trang 5<head id=”Head1” runat=”server”>
<style type=”text/css”>
.movies
{
border:Solid 1px black;
}
.movies td,.movies th
{
padding:5px;
}
</style>
<title>Show Movies by Category</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:DropDownList
id=”ddlMovieCategory”
DataSourceID=”srcMovieCategories”
DataTextField=”Name”
DataValueField=”Id”
ToolTip=”Movie Category”
Runat=”server” />
<asp:Button
id=”btnSelect”
Text=”Select”
Runat=”server” />
<asp:GridView
id=”grdMovies”
DataSourceID=”srcMovies”
CssClass=”movies”
GridLines=”None”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovieCategories”
TypeName=”MovieCategories”
SelectMethod=”GetCategories”
Runat=”server” />
<asp:ObjectDataSource
id=”srcMovies”
TypeName=”MovieCategories”
SelectMethod=”GetMovies”
Trang 6Runat=”server”>
<SelectParameters>
<asp:ControlParameter
Name=”CategoryId”
ControlID=”ddlMovieCategory” />
</SelectParameters>
</asp:ObjectDataSource>
</div>
</form>
</body>
</html>
The ObjectDataSource control in Listing 18.14 is bound to the component contained in
Listing 18.15 The ObjectDataSource control includes a SelectParameters collection The
SelectParameters collection contains a ControlParameter, which represents the current
value of the ddlMovieCategory DropDownList control
LISTING 18.15 MovieCategories.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public class MovieCategories
{
private readonly string _conString;
public SqlDataReader GetMovies(int categoryId)
{
// Create Connection
SqlConnection con = new SqlConnection(_conString);
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “SELECT Id,Title,Director,DateReleased “
+ “ FROM Movies WHERE CategoryId=@CategoryId”;
// Add parameters
cmd.Parameters.AddWithValue(“@CategoryId”, categoryId);
// Return DataReader
con.Open();
Trang 7return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public SqlDataReader GetCategories()
{
// Create Connection
SqlConnection con = new SqlConnection(_conString);
// Create Command
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = “SELECT Id,Name FROM MovieCategories”;
// Return DataReader
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
public MovieCategories()
{
_conString =
WebConfigurationManager.ConnectionStrings[“Movies”].ConnectionString;
}
}
Passing Objects as Parameters
Passing long lists of parameters to methods can make it difficult to maintain an
applica-tion If the list of parameters changes, you need to update every method that accepts the
list of parameters Rather than pass a list of parameters to a method, you can pass a
partic-ular object For example, you can pass a CompanyEmployee object to a method used to
update an employee, rather than a list of parameters that represent employee properties
If you specify a value for an ObjectDataSource control’s DataObjectTypeName property,
you can pass an object rather than a list of parameters to the methods that an
ObjectDataSource represents In that case, the ObjectDataSource parameters represent
properties of the object
For example, the EmployeeData component in Listing 18.16 contains an InsertEmployee()
method for creating a new employee This method is passed an instance of the
CompanyEmployee object that represents a particular employee The CompanyEmployee class
also is included in Listing 18.16
Trang 8LISTING 18.16 EmployeeData.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.Configuration;
public class EmployeeData
{
string _connectionString;
public void UpdateEmployee(CompanyEmployee employeeToUpdate)
{
// Initialize ADO.NET objects
SqlConnection con = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = “UPDATE Employees SET FirstName=@FirstName,” +
“LastName=@LastName,Phone=@Phone WHERE Id=@Id”;
cmd.Connection = con;
// Create parameters
cmd.Parameters.AddWithValue(“@Id”, employeeToUpdate.Id);
cmd.Parameters.AddWithValue(“@FirstName”, employeeToUpdate.FirstName);
cmd.Parameters.AddWithValue(“@LastName”, employeeToUpdate.LastName);
cmd.Parameters.AddWithValue(“@Phone”, employeeToUpdate.Phone);
// Execute command
using (con)
{
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<CompanyEmployee> GetEmployees()
{
List<CompanyEmployee> employees = new List<CompanyEmployee>();
SqlConnection con = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = “SELECT Id,FirstName,LastName,Phone FROM Employees”;
cmd.Connection = con;
using (con)
{
con.Open();
Trang 9SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
CompanyEmployee newEmployee = new CompanyEmployee();
newEmployee.Id = (int)reader[“Id”];
newEmployee.FirstName = (string)reader[“FirstName”];
newEmployee.LastName = (string)reader[“LastName”];
newEmployee.Phone = (string)reader[“Phone”];
employees.Add(newEmployee);
}
}
return employees;
}
public EmployeeData()
{
_connectionString =
WebConfigurationManager.ConnectionStrings[“Employees”].ConnectionString;
}
}
public class CompanyEmployee
{
private int _id;
private string _firstName;
private string _lastName;
private string _phone;
public int Id
{
get { return _id; }
set { _id = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
Trang 10public string Phone
{
get { return _phone; }
set { _phone = value; }
}
}
The page in Listing 18.17 contains a DetailsView control and an ObjectDataSource
control The DetailsView control enables you to update existing employees in the
Employees database table
LISTING 18.17 UpdateEmployees.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>Update Employees</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:DetailsView ID=”DetailsView1”
DataSourceID=”srcEmployees”
DataKeyNames=”Id”
AutoGenerateRows=”True”
AutoGenerateEditButton=”True”
AllowPaging=”true”
Runat=”server” />
<asp:ObjectDataSource
id=”srcEmployees”
TypeName=”EmployeeData”
DataObjectTypeName=”CompanyEmployee”
SelectMethod=”GetEmployees”
UpdateMethod=”UpdateEmployee”
Runat=”server” />
</div>
</form>
</body>
</html>