Recipe 2.22. Displaying a Pop-Up Details Window


Problem

You want to provide additional details for each row in a GridView using a pop-up window.

Solution

Add a Details button to each row in the GridView. When the user clicks the button, open a new browser window, obtain the information from the server, and display the detailed information in a pop-up window. An example of the possible output is shown in Figures 2-23 (sample GridView) and Figures 2-24 (sample pop-up window output). As with the other recipes in this book, we've implemented a complete application that illustrates this approach. The form and code-behind for the page containing the sample GridView is shown in Examples 2-57, 2-58 through 2-59, and the form and code-behind for the sample pop-up window is shown in Examples 2-60, 2-61 through 2-62.

Figure 2-23. GridView with pop-up details window output


Discussion

To implement this solution, create a GridView in the normal fashion but add a link button column to display a Details link. When the user clicks the Details link within a row of the GridView, the browser opens a new window and requests the appropriate page from the server. In the context of our example that implements this solution, a book details page is requested. From here on, the recipe's remaining steps are described in the context of our example because we use techniques that you are likely to find helpful in implementing your own application.

In our example, when the book details page is processed, a book ID is extracted from the query string and is used in the database query to get the detailed data for the specific book as shown in the Page_Load method of Examples 2-61 (VB) and 2-62 (C#).

Figure 2-24. Pop-up details window output


When building a Details link in the .aspx file, an HTML anchor tag is placed in the ItemTemplate for the column. (The purpose of the anchor tag is to request the details page when the associated link button is clicked.) The target property of the HTML anchor is set to _blank, causing a new browser window to open when the link is clicked.

The Page_Load method in the code-behind is nearly identical to that used in other recipes with one change. The lines of code shown next are added to populate the DataKeyNames collection of the GridView with the primary key values for the rows being displayed. This causes the GridView to keep track of the primary key value for each row without our having to output the data in a hidden column. These values are needed later to display the book details.

 

dataKeys(0) = "BookID" gvBooks.DataKeyNames = dataKeys

dataKeys = new string[1] {"BookID"}; gvBooks.DataKeyNames = dataKeys;

The GridView control's RowDataBound event is used to set the href value for the "details" HTML anchors added to the GridView. Because this event is called independently for every row in the GridView, the item type must be checked to see if this event applies for a given data row.

When the event does apply to a data row, the first thing we must do is get the ID of the book being displayed in the row as shown here:

 

bookID = CInt(gvBooks.DataKeys(e.Row.RowIndex).Item(0))

bookID = (int)(gvBooks.DataKeys[e.Row.RowIndex][0]);

Next, we need to get a reference to the "details" HTML anchor in the row. Because ItemTemplate were used and the anchor controls in the templates were given IDs, we can accomplish this by using the FindControl method of the passed item. If a standard BoundField were used instead, the data would have to be accessed using the cells collection (e.g., e.Row.Cells(1).controls(1) would access the anchor control in this example). Providing an ID and using FindControl eliminates the potential for broken code if the columns are later reordered. The control must be cast to an HTMLAnchor because the controls collection is a collection of objects.

After obtaining a reference to the HTML anchor tag, we need to set the href property of the anchor to the name of the details page. In addition, the URL needs to include "BookID= n" where n is the ID of the book displayed in the row. The resulting anchor tag in the GridView for BookID = 1 is shown here:

 <a href="CH02BookDetailsVB.aspx?BookID=1"          target="_blank">Details</a> 

The ID is altered by ASP.NET to ensure all server controls have unique IDs. ASP.NET maintains the original and the unique IDs, so the original ID we provided with the FindControl method is handled correctly, sparing us from determining the unique ID or dealing with indexing into items and cells.


Example 2-57. GridView with pop-up details window (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02GridViewWithPopupDetailsVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02GridViewWithPopupDetailsVB" Title="GridView With Popup Details" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" >   GridView With Popup Details (VB) </div> <asp:GridView  Runat="Server"   AllowPaging="false"   AllowSorting="false"   AutoGenerateColumns="false"   BorderColor="#000080"   BorderStyle="Solid"   BorderWidth="2px"   Caption=""   HorizontalAlign="Center"   Width="90%"   OnRowDataBound="gvBooks_RowDataBound" >     <HeaderStyle HorizontalAlign="Center" Css /> <RowStyle css /> <AlternatingRowStyle css /> <SelectedRowStyle Css /> <Columns> <asp:BoundField HeaderText="Title" DataField="Title" ItemStyle-HorizontalAlign="Left" /> <asp:TemplateField ItemStyle-HorizontalAlign="Center">   <ItemTemplate>     <a  runat="server" target="_blank">Details</a>   </ItemTemplate> </asp:TemplateField> </Columns>   </asp:GridView> </asp:Content> 

Example 2-58. GridView with pop-up details window code-behind (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02GridViewWithPopupDetailsVB.aspx ''' </summary> Partial Class CH02GridViewWithPopupDetailsVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim dSource As SqlDataSource = Nothing Dim dataKeys(0) As String If (Not Page.IsPostBack) Then 'configure the data source to get the data from the database dSource = New SqlDataSource( ) dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataReader dSource.ProviderName = "System.Data.OleDb" dSource.SelectCommand = "SELECT BookID, Title " & _ "FROM Book " & _ "ORDER BY Title" 'set the source of the data for the gridview control and bind it dataKeys(0) = "BookID" gvBooks.DataKeyNames = dataKeys gvBooks.DataSource = dSource gvBooks.DataBind( ) End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine is the event handler that is called for each item in the ''' GridView after a data bind occurs. It is responsible for setting the ''' URL of the anchor tags to the page used to display the details for ''' a book ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub gvBooks_RowDataBound(ByVal sender As Object, ByVal e As _ System.Web.UI.WebControls.GridViewRowEventArgs) Const DETAIL_PAGE As String = "CH02BookDetailsVB.aspx" Dim bookID As Integer Dim anchor As HtmlAnchor 'check the type of item that was databound and only take action if it 'was a row in the GridView If (e.Row.RowType = DataControlRowType.DataRow) Then 'get the book ID for the row being bound bookID = CInt(gvBooks.DataKeys(e.Row.RowIndex).Item(0)) 'get the anchor tag in the row 'NOTE: This can be done by using the FindControl method of the passed ' item because ItemTemplates were used and the anchor controls in ' the templates where given IDs. If a standard BoundField was ' used, the data would have to be accessed using the cells ' collection (e.g. e.Row.Cells(1).controls(1) would access the ' anchor control in this example. anchor = CType(e.Row.FindControl("lnkDetails"), _ HtmlAnchor) 'set the URL of the anchor tag to the page used to display the book 'details passing the ID of the book in the querystring anchor.HRef = DETAIL_PAGE & "?Booktitle-IDAB3PQ1">Example 2-59. GridView with pop-up details window code-behind (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02GridViewWithPopupDetailsCS.aspx /// </summary> public partial class CH02GridViewWithPopupDetailsCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { SqlDataSource dSource = null; String[] dataKeys; if (!Page.IsPostBack) { // configure the data source to get the data from the database dSource = new SqlDataSource( ); dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataReader; dSource.ProviderName = "System.Data.OleDb"; dSource.SelectCommand = "SELECT BookID, Title " + "FROM Book " + "ORDER BY Title"; // set the source of the data for the gridview control and bind it dataKeys = new string[1] {"BookID"}; gvBooks.DataKeyNames = dataKeys; gvBooks.DataSource = dSource; gvBooks.DataBind( ); } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the GridView's row created /// event. It is responsible for setting the icon in the header row to /// indicate the current sort column and sort order /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void gvBooks_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) { const String DETAIL_PAGE = "CH02BookDetailsCS.aspx"; int bookID; HtmlAnchor anchor; // check the type of item that was databound and only take action if it // was a row in the GridView if (e.Row.RowType == DataControlRowType.DataRow) { // get the book ID for the row being bound bookID = (int)(gvBooks.DataKeys[e.Row.RowIndex][0]); // 'get the anchor tag in the row // NOTE: This can be done by using the FindControl method of the // passed item because ItemTemplates were used and the // anchor controls in the templates where given IDs. If a // standard BoundField was used, the data would have to be // accessed using the cells collection (e.g. // e.Row.Cells[1].controls[1] would access the anchor control // in this example. anchor = (HtmlAnchor)(e.Row.FindControl("lnkDetails")); // set the URL of the anchor tag to the page used to display the book // details passing the ID of the book in the querystring anchor.HRef = DETAIL_PAGE + "?Booktitle-IDA23PQ1">Example 2-60. Pop-up detail page (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02BookDetailsVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02BookDetailsVB" Title="Book Details" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > Book Details (VB) </div> <asp:FormView  runat="server" HorizontalAlign="Center">   <ItemTemplate> <table width="600" border="0">   <tr> <td rowspan="6" align="center" width="250">   <img src="/books/1/505/1/html/2/images/books/<%#Eval("ImageFilename") %>"alt="Book"></td> <td  width="150">Title: </td> <td  width="325"><%#Eval("Title") %></td>   </tr>   <tr> <td >ISBN: </td> <td ><%#Eval("ISBN") %></td>   </tr>   <tr> <td >Publisher: </td> <td ><%#Eval("Publisher") %></td>   </tr>   <tr>     <td >Publish Date: </td> <td ><%#Eval("PublishDate", "{0:MMM yyyy}") %></td>   </tr>   <tr> <td >List Price: </td> <td ><%#Eval("ListPrice") %></td>   </tr>   <tr> <td >Discounted Price: </td> <td ><%#Eval("DiscountedPrice") %></td>   </tr> </table>  </ItemTemplate>    </asp:FormView> </asp:Content> 

Example 2-61. Pop-up detail page code-behind (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02BookDetailsVB.aspx ''' </summary> Partial Class CH02BookDetailsVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Dim dSource As SqlDataSource = Nothing Dim param As Parameter Dim bookID As String If (Not Page.IsPostBack) Then 'get the book ID from the querystring in the URL If (IsNothing(Request.QueryString.Item("BookID"))) Then 'production code needs to handle the page request without the needed 'information in the querystring here Else bookID = Request.QueryString.Item("BookID").ToString( ) 'configure the data source to get the data from the database dSource = New SqlDataSource( ) dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataReader dSource.ProviderName = "System.Data.OleDb" dSource.SelectCommand = "SELECT Title, ISBN, Publisher, " & _ "PublishDate, ListPrice, " & _ "DiscountedPrice, ImageFilename " & _ "FROM Book " & _ "WHERE BookID=?" param = New Parameter("BookID", TypeCode.Int32, bookID) dSource.SelectParameters.Add(param) 'set the source of the data for the formview control and bind it fvBook.DataSource = dSource fvBook.DataBind( ) End If End If End Sub 'Page_Load End Class 'CH02BookDetailsVB End Namespace 

Example 2-62. Pop-up detail page code-behind (.cs)

 using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02BookDetailsCS.aspx /// </summary> public partial class CH02BookDetailsCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { SqlDataSource dSource = null; Parameter param = null; String bookID; if (!Page.IsPostBack) { // get the book ID from the querystring in the URL if (Request.QueryString["BookID"] == null) { // production code needs to handle the page request without the // needed information in the querystring here } else { bookID = Request.QueryString["BookID"].ToString( ); // configure the data source to get the data from the database dSource = new SqlDataSource( ); dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataReader; dSource.ProviderName = "System.Data.OleDb"; dSource.SelectCommand = "SELECT Title, ISBN, Publisher, " + "PublishDate, ListPrice, " + "DiscountedPrice, ImageFilename " + "FROM Book " + "WHERE BookID=?"; param = new Parameter("BookID", TypeCode.Int32, bookID); dSource.SelectParameters.Add(param); // set the source of the data for the gridview control and bind it fvBook.DataSource = dSource; fvBook.DataBind( ); } } } // Page_Load } // CH02BookDetailsCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net