1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET 4 Unleased - p 43 ppsx

10 182 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 790,79 KB

Nội dung

ptg 394 LISTING 9.9 ShowMovieCount.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”> <style type=”text/css”> .gridView { margin:0px auto; border:solid 4px black; background-color:white; } .gridView td, .gridView th { padding:20px; } html { background-color:silver; font-family:Georgia, Serif; } </style> <title>Show Movie Count</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:GridView id=”grdMovies” DataSourceID=”srcMovies” CssClass=”gridView” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” SelectCommand=”CountMoviesInCategory” SelectCommandType=”StoredProcedure” ConnectionString=”<%$ ConnectionStrings:Movies %>” Runat=”server” /> CHAPTER 9 Using the SqlDataSource Control From the Library of Wow! eBook ptg 395 Executing Database Commands 9 </div> </form> </body> </html> Filtering Database Rows The SqlDataSource control includes a FilterExpression property that enables you to filter the rows returned by the control. You can define complex Boolean filters that include parameters with this property. For example, the page in Listing 9.10 retrieves all movies that have titles that match the string entered into the TextBox control (see Figure 9.6). LISTING 9.10 ShowFilterExpression.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”> <style type=”text/css”> FIGURE 9.6 Show matching movies. From the Library of Wow! eBook ptg 396 CHAPTER 9 Using the SqlDataSource Control td, th { padding:10px; } </style> <title>Show Filter Expression</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:TextBox id=”txtTitle” Runat=”server” /> <asp:Button id=”btnMatch” Text=”Match” Runat=”server” /> <hr /> <asp:GridView id=”grdMovies” DataSourceId=”srcMovies” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” SelectCommand=”SELECT Id,Title,Director,DateReleased FROM Movies” FilterExpression=”Title LIKE ‘{0}%’” ConnectionString=”<%$ ConnectionStrings:Movies %>” Runat=”server”> <FilterParameters> <asp:ControlParameter Name=”Title” ControlID=”txtTitle” /> </FilterParameters> </asp:SqlDataSource> </div> </form> </body> </html> In Listing 9.10, the FilterExpression includes the LIKE operator and the % wildcard char- acter. The LIKE operator performs partial matches on the movie titles. From the Library of Wow! eBook ptg 397 Executing Database Commands 9 The filter expression includes a {0} placeholder. The value of the txtTitle TextBox is plugged into this placeholder. You can use multiple parameters and multiple placeholders with the FilterExpression property. NOTE Behind the scenes, the SqlDataSource control uses the DataView.RowFilter proper- ty 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. Using the FilterExpression property is especially useful when caching the data repre- sented by a SqlDataSource. For example, you can cache the entire contents of the movies database table in memory and use the FilterExpression property to filter the movies displayed on a page. You can display different sets of movies depending on a user’s selec- tion from a drop-down list of movie categories. Changing the Data Source Mode The SqlDataSource control can represent the data that it retrieves in two different ways. It can represent the data using either an ADO.NET DataSet or an ADO.NET DataReader. By default, the SqlDataSource represents records using the ADO.NET DataSet object. The DataSet object provides a static, memory-resident representation of data. NOTE Technically, the SqlDataSource control returns a DataView and not a DataSet. Because, by default, the SqlDataSourceMode enumeration is set to the value DataSet, I continue to refer to DataSets instead of DataViews. Some features of the DataBound controls work only when the controls are bound to a DataSet. For example, the GridView control supports client-side sorting and filtering only when the control is bound to a DataSet. The other option is to represent the data that a SqlDataSource control returns with a DataReader object. The advantage of using DataReader is that it offers significantly better performance than the DataSet object. The DataReader represents a fast, forward-only representation of data. If you want to grab some database records and display the records in the fastest possible way, use the DataReader object. For example, the page in Listing 9.11 retrieves the records from the Movies database by using DataReader. From the Library of Wow! eBook ptg 398 CHAPTER 9 Using the SqlDataSource Control LISTING 9.11 ShowDataSourceMode.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 Data Source Mode</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:GridView id=”grdMovies” DataSourceID=”srcMovies” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” DataSourceMode=”DataReader” SelectCommand=”SELECT * FROM Movies” ConnectionString=”<%$ ConnectionStrings:Movies %>” Runat=”server” /> </div> </form> </body> </html> The SqlDataSource control’s DataSourceMode property is set to the value DataReader. Handling SQL Command Execution Errors Whenever you build a software application, you need to plan for failure. Databases go down, users enter unexpected values in form fields, and networks get clogged. It is miracu- lous that the Internet works at all. You can handle errors thrown by the SqlDataSource control by handling any or all of the following four events: . Deleted—Happens immediately after the SqlDataSource executes its delete command. . Inserted—Happens immediately after the SqlDataSource executes its insert command. From the Library of Wow! eBook ptg 399 Executing Database Commands 9 . Selected—Happens immediately after the SqlDataSource executes its select command. . Updated—Happens immediately after the SqlDataSource executes its delete command. Each of these events is passed an EventArgs parameter that includes any exceptions raised when the command was executed. For example, in the SELECT command in Listing 9.12, movies are retrieved from the DontExist database table instead of the Movies data- base table. LISTING 9.12 HandleError.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_Selected(object sender, SqlDataSourceStatusEventArgs e) { if (e.Exception != null) { lblError.Text = e.Exception.Message; e.ExceptionHandled = true; } } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> <style type=”text/css”> .error { display:block; color:red; font:bold 16px Arial; margin:10px; } </style> <title>Handle Error</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:Label From the Library of Wow! eBook ptg 400 CHAPTER 9 Using the SqlDataSource Control id=”lblError” EnableViewState=”false” CssClass=”error” Runat=”server” /> <asp:GridView id=”grdMovies” DataSourceID=”srcMovies” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” SelectCommand=”SELECT * FROM DontExist” ConnectionString=”<%$ ConnectionStrings:Movies %>” OnSelected=”srcMovies_Selected” Runat=”server” /> </div> </form> </body> </html> If the page in Listing 9.12 is opened in a web browser, an exception is raised when the SqlDataSource control attempts to retrieve the rows from the DontExist database table. (Because it doesn’t exist.) In the srcMovies_Selected() method, the exception is detected and displayed in a Label control. The ExceptionHandled property suppresses the exception. If you do not set ExceptionHandled to true, the page explodes (see Figure 9.7). As an alternative to handling exceptions at the level of the SqlDataSource control, you can handle the exception at the level of a DataBound control. The GridView, DetailsView, and FormView controls all include events that expose the Exception and ExceptionHandled properties. For example, the page in Listing 9.13 includes a GridView that handles the exception raised when you attempt to edit the contents of the DontExist database table. From the Library of Wow! eBook ptg 401 Executing Database Commands 9 LISTING 9.13 GridViewHandleError.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 grdMovies_RowUpdated(object sender, GridViewUpdatedEventArgs e) { if (e.Exception != null) { lblError.Text = e.Exception.Message; e.ExceptionHandled = true; } } </script> <html xmlns=”http://www.w3.org/1999/xhtml” > <head id=”Head1” runat=”server”> FIGURE 9.7 An unhandled exception. From the Library of Wow! eBook ptg 402 CHAPTER 9 Using the SqlDataSource Control <style type=”text/css”> .error { display:block; color:red; font:bold 16px Arial; margin:10px; } </style> <title>GridView Handle Error</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:Label id=”lblError” EnableViewState=”false” CssClass=”error” Runat=”server” /> <asp:GridView id=”grdMovies” DataKeyNames=”Id” AutoGenerateEditButton=”true” DataSourceID=”srcMovies” OnRowUpdated=”grdMovies_RowUpdated” Runat=”server” /> <asp:SqlDataSource id=”srcMovies” SelectCommand=”SELECT Id,Title FROM Movies” UpdateCommand=”UPDATE DontExist SET Title=@Title WHERE Id=@ID” ConnectionString=”<%$ ConnectionStrings:Movies %>” Runat=”server” /> </div> </form> </body> </html> From the Library of Wow! eBook ptg 403 Executing Database Commands 9 After you open the page in Listing 9.13, you can click the Edit link next to any record to edit the record. If you click the Update link, an exception is raised because the update command attempts to update the DontExist database table. The exception is handled by the GridView control’s RowUpdated event handler. You can handle an exception at both the level of the SqlDataSource control and the level of a DataBound control. The SqlDataSource control’s events are raised before the corre- sponding events are raised for the DataBound control. If you handle an exception by using the ExceptionHandled property in the SqlDataSource control’s event handler, the excep- tion is not promoted to the DataSource control’s event handler. Canceling Command Execution You can cancel SqlDataSource commands when some criterion is not met. For example, you might want to validate the parameters that you use with the command before execut- ing the command. You can cancel a command by handling any of the following events exposed by the SqlDataSource control: . Deleting—Happens immediately before the SqlDataSource executes its delete command. . Filtering—Happens immediately before the SqlDataSource filters its data. . Inserting—Happens immediately before the SqlDataSource executes its insert command. . Selecting—Happens immediately before the SqlDataSource executes its select command. . Updating—Happens immediately before the SqlDataSource executes its delete command. For example, the page in Listing 9.14 contains a DetailsView control bound to a SqlDataSource control that represents the contents of the Movies database table. The DetailsView control enables you to update a particular movie record; however, if you leave one of the fields blank, the update command is canceled (see Figure 9.8). From the Library of Wow! eBook . syntax by looking up the DataColumn.Expression property in the .NET Framework SDK Documentation. Using the FilterExpression property is especially useful when caching the data repre- sented by a. method, the exception is detected and displayed in a Label control. The ExceptionHandled property suppresses the exception. If you do not set ExceptionHandled to true, the page explodes (see Figure. ShowFilterExpression.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”

Ngày đăng: 06/07/2014, 18:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN