To create a paging control for ASP.net

Source: Internet
Author: User
Tags bool eval html tags microsoft sql server sql server query range sort valid
asp.net| Create | pagination | Control from a programmer's perspective, Microsoft SQL Server? One of the biggest drawbacks of a query is that the number of rows returned is usually much more than the number of rows that the application's user interface can actually hold. This embarrassing situation often put developers in trouble. Should the developer create a very long page, let the user take time to scroll through it, or should we set up a manual paging mechanism to better solve the problem?
Which solution is better depends largely on the nature of the data being retrieved. A long list of items, such as search results, that are best displayed by multiple pages of equal size and relatively short per page. A long list of individual items, such as the text of an article, that is easier to use if the entire insert is in one page. The final analysis is that decisions should be made based on the overall use of the application. So how does Microsoft asp.net solve data paging problems?

asp.net provides powerful data-bound controls to format query results as HTML tags. However, only one control in these data-bound controls, the DataGrid control, would otherwise support paging. Other controls, such as DataList, Repeater, or CheckBoxList, do not support paging. These controls and other list controls do not support paging, not because they do not support paging in structure, but because they are different from the DataGrid and do not contain any specific code that handles paging. However, the code that processes the paging is fairly boilerplate and can be added to all of these controls.

Scott Mitchell, in a recent article titled "Creating a Pageable, sortable DataGrid," describes the DataGrid paging. This article also references other useful information on the Web, providing you with the basics and other information about grid pagination. If you want to see an example of how to make a DataList control available for pagination, you can view this article in English. This article demonstrates how to create a custom DataList control that has the current index and page size properties and can initiate page change events.

The same code can also be used to meet paging needs of other list controls, such as ListBox and CheckBoxList. However, it is not really a good idea to add paging functionality to individual controls, because, as mentioned, the paging code is fairly boilerplate. So what's the best way for smart programmers to get all of the paging capabilities of all these controls with a new generic pager control?

This article establishes a paging program control that enables the Partner List control to page through SQL Server query results. The control, named SqlPager, supports two types of partner controls-list controls and underlying data list controls.

Notable features of SqlPager controls

The SqlPager control is an ASP. NET composite control, containing a single row table. The row also contains two cells-navigation bars and page descriptors. The user interface of the control is striped, ideally with the same width as the partner control. The Navigation Bar section provides clickable elements to move between pages, and the page Descriptor section provides users with some feedback about the currently displayed page.




Like the embedded paging program for the DataGrid control, the SqlPager control has two navigation modes, the next/previous page, and the number page. In addition, its special properties PagerStyle enable you to choose a more convenient style. This control works in conjunction with the list control. You can specify one of these collaborators controls for a paging program by ControlToPaginate string properties.

Sqlpager1.controltopaginate = "ListBox1";
In general, the paging program first obtains the query results of SQL Server, prepares an appropriate record page, and then displays the page through the DataSource property of the partner control. When the user clicks to view a new page, the pager retrieves the requested data and again displays the data through the partner control. The paging mechanism is completely transparent to the list control. The data source for a list control is updated programmatically and contains only those records that are appropriate for the current page.

The paging engine of a control has several public properties, such as CurrentPageIndex, ItemsPerPage, and PageCount, that are used to get and set the index of the current page, the size of each page, and the total number of pages to display. The paging program manages any logic required for data retrieval and paging.

The SelectCommand property sets the command text used to get the data. The ConnectionString property defines the name and location of the database and the connection credentials. The way in which the query is executed depends on the value of the Pagingmode property. The possible value of this property is the value of the Pagingmode enumeration with the same name-Cached and noncached. If you select the Cached option, the entire result set is retrieved using the data adapter and the DataTable object. You can choose to place the result set in the ASP.net cache object, which can be reused until it expires. If you select the noncached option, the query retrieves only the records that are appropriate for the current page. At this point, no data is placed in the Cache of ASP.net. The noncached mode is almost identical to the custom paging mode of the DataGrid control.

The following table lists all programming interfaces for the SqlPager control.

Table 1:sqlpager control's programming interface

The name Type Description CacheDuration property indicates the number of seconds that the data is persisted in the asp.net cache. For Cached mode only. The default value is 60. The ConnectionString property is used to access the connection string for the selected SQL Server database. ControlToPaginate Property The control ID in the same. aspx page, which displays the record page retrieved by the paging program. This is the collaborators control. The CurrentPageIndex property gets and sets the page index based on 0. ItemsPerPage property gets and sets the number of records to display per page. The default value displays 10 items per page. PagerStyle Property This value indicates the style of the paging program user interface. It can be one of the PagerStyle enumeration values: Nextprev and NumericPages. In Nextprev mode, VCR-style buttons are displayed to go to the first, previous, Next, and last pages. In numericpages mode, a drop-down list is displayed that lists the indexes for all available pages. Pagingmode Property This value indicates how data is retrieved. It can be one of the Pagingmode enumeration values: Cached and noncached. If Cached, the data adapter is used and the entire result set is temporarily placed in the ASP.net cache. If noncached, only the records in the current page are retrieved. In this case, caching is not done. The text of the command used by the SelectCommand property to query. Preferably a select-from-where form. The ORDER BY clause is not supported. The sort is specified separately by the SortField property. The name of the field that the SortField property is used to sort. This field is used to provide a dynamic ORDER BY clause for a query. The sort is executed by SQL Server. The ClearCache method deletes any data stored in the ASP.net cache. PageIndexChanged Event Default event that occurs when the paging program moves to another page. The data structure of the event is the Pagechangedeventargs class, which contains the index of the old page and the new page.
Because the SqlPager control inherits WebControl, it also has a number of UI-related properties to manage fonts, borders, and colors.





Generating SqlPager controls

will be used as a composite control to generate the SqlPager control and let it inherit the WebControl class. A composite control is specific to a ASP.net server control and is made up of one or more server controls.

public class Sqlpager:webcontrol, INamingContainer
{ ... }
Unless you build a fully customized control or extend an existing control, most of the time you create a new control is actually building a composite control. To create a SqlPager, combine a Table control and combine several LinkButton controls or a DropDownList control based on the style of the pager.

There are several principles to be aware of when building a composite control. First, you need to overwrite the CreateChildControls protected method. The CreateChildControls method is inherited from the control, which is called when server controls want to create a child control for display, or when they return.

protected override void CreateChildControls ()
{
Clear existing child controls and their ViewState
Controls.clear ();
Clearchildviewstate ();

Building the control tree
Buildcontrolhierarchy ();
}
When overriding this method, several important actions need to be performed. Create and initialize any required child control instances and add them to the Controls collection of the parent control. However, before you can build a new control tree, you should delete any existing child controls and clear any ViewState information that the child controls may leave behind.

The composite component also needs to implement the INamingContainer interface so that the ASP.net runtime can create a new named range for it. This ensures that all controls in the composite control have unique names. This will also ensure that the child control's return data can be automatically processed.

It is important to be a naming container for SqlPager controls. In fact, SqlPager contains some LinkButton controls and needs to get and handle their click events to navigate the page. As with any other control in the ASP.net page, LinkButton is given an ID that identifies the control that handles the returned event.

When processing a return event, the ASP.net runtime attempts to find a match between the target ID of the event and any direct child controls of the main form. LinkButton is a child of the paging program, so it cannot run its server-side code. Does this mean that only a direct child control of a form can start and handle server events? Of course not, as long as you use a naming container.

You can change the actual ID of an inline link button from "A" to "Sqlpager1:first" by enabling the SqlPager control to implement the INamingContainer interface. When the user clicks to view a new page, the return event takes Sqlpager1:first as the target control. In fact, the algorithm used by the runtime to identify the target control is more complex than the description above. The runtime considers the name of the event target control to be a colon-delimited string. In fact, this match is between the child controls of a form and the first token of a colon-delimited string, such as Sqlpager1:first. Because the paging program is a child of a form, it succeeds when the page is matched, and the pager gets the click event. If you think this explanation is not sufficient or confusing, simply download the source code for the SqlPager control, delete the INamingContainer markup interface, and recompile. You will see that the paging program can return, but you cannot handle the Click event internally.

The INamingContainer interface is a markup interface that does not have a method, and its implementation simply specifies the name in the class declaration without any other action.

Another important aspect of composite controls is that they typically do not require custom logic to be displayed. The display of a composite control follows the display of its constituent controls. When you build a composite control, you typically do not need to overwrite the Render method.

The SqlPager tree of a control consists of a single row table that contains two cells. This table inherits most of the visual settings for the pager, such as foreground and background colors, borders, font information, and width. The first cell contains the navigation bar, and its structure depends on the value of the PagerStyle property. If the pager style is Nextprev, the navigation bar will consist of four VCR-style buttons. Otherwise, it will be made up of a drop-down list.

private void Buildcontrolhierarchy ()
{
Generate Environment table (one row, two cells)
Table T = new table ();
T.font.name = this. Font.Name;
T.font.size = this. Font.Size;
T.borderstyle = this. BorderStyle;
T.borderwidth = this. BorderWidth;
T.bordercolor = this. bordercolor;
T.width = this. Width;
T.height = this. Height;
T.backcolor = this. BackColor;
T.forecolor = this. ForeColor;

To generate a row in a table
TableRow row = new TableRow ();
T.rows.add (row);

To generate a cell with a navigation bar
TableCell cellnavbar = new TableCell ();
if (PagerStyle = = this. Pagerstyle.nextprev)
Buildnextprevui (Cellnavbar);
Else
Buildnumericpagesui (Cellnavbar);
Row. Cells.add (Cellnavbar);

To generate a cell with a page index
TableCell cellpagedesc = new TableCell ();
Cellpagedesc.horizontalalign = Horizontalalign.right;
Buildcurrentpage (CELLPAGEDESC);
Row. Cells.add (CELLPAGEDESC);

Add a table to the control tree
This. Controls.Add (t);
}
Adding individual controls to the correct Controls collection is extremely important for the correct display of paging programs. The outermost table must be added to the Controls collection of the paging program. The link buttons and Drop-down lists must be added to the Controls collection of the corresponding table cells.

The code used to generate the link button navigation bar is given below. Each button displays a webdings character that can be disabled as needed and bound to the internal Click event handler.

private void Buildnextprevui (TableCell cell)
{
BOOL Isvalidpage = ((CurrentPageIndex >=0) &&
(CurrentPageIndex <= TotalPages-1));
BOOL Canmoveback = (currentpageindex>0);
BOOL Canmoveforward = (currentpageindex<totalpages-1);

Show << button
LinkButton-New LinkButton ();
First.id = "a";
First. Click + + new EventHandler (First_click);
First. Font.Name = "Webdings";
First. Font.Size = Fontunit.medium;
First. ForeColor = ForeColor;
First. TOOLTIP = "First page";
First. Text = "7";
First. Enabled = Isvalidpage && canmoveback;
Cell. Controls.Add (a);
:
}
The build method for a different style of the paging program (the number page listed in the Drop-down list) is as follows:

private void Buildnumericpagesui (TableCell cell)
{
Display a drop-down list
DropDownList pagelist = new DropDownList ();
Pagelist.id = "PageList";
Pagelist.autopostback = true;
Pagelist.selectedindexchanged + = new EventHandler (Pagelist_click);
PageList.Font.Name = this. Font.Name;
PageList.Font.Size = Font.Size;
Pagelist.forecolor = ForeColor;

if (TotalPages <=0 | | CurrentPageIndex = =-1)
{
PAGELIST.ITEMS.ADD ("No pages");
pagelist.enabled = false;
Pagelist.selectedindex = 0;
}
else//Fill list
{
for (int i=1; i<=totalpages; i++)
{
ListItem item = new ListItem (i.ToString (), (i-1). ToString ());
PAGELIST.ITEMS.ADD (item);
}
Pagelist.selectedindex = CurrentPageIndex;
}
}
All event handlers (Click and SelectedIndexChanged) will eventually change the currently displayed page. Both of these methods invoke a public private method GoToPage.

private void First_click (object sender, EventArgs e)
{
GoToPage (0);
}
private void Pagelist_click (object sender, EventArgs e)
{
DropDownList pagelist = (DropDownList) sender;
int pageIndex = Convert.ToInt32 (PageList.SelectedItem.Value);
GoToPage (PageIndex);
}
private void GoToPage (int pageIndex)
{
Preparing event data
Pagechangedeventargs e = new Pagechangedeventargs ();
E.oldpageindex = CurrentPageIndex;
E.newpageindex = PageIndex;

Update the current index
CurrentPageIndex = PageIndex;

Start Page Change events
Onpageindexchanged (e);

Bind new Data
DataBind ();
}
The handler for the other navigation buttons differs only from the first_click in that they are passed to the GoToPage method with different page numbers. The GoToPage method handles the PageIndexChanged event and is responsible for initiating the data-binding process. It prepares event data (old pages and new page indexes) and triggers events. GoToPage is defined as private, but you can use the CurrentPageIndex property to programmatically change the displayed page.

public int CurrentPageIndex
{
get {return Convert.ToInt32 (viewstate["CurrentPageIndex"]);}
set {viewstate["CurrentPageIndex"] = value;}
}
As with all the properties listed in Table 1, the CurrentPageIndex property implementation is fairly straightforward. It saves its contents to the ViewState and restores it from it. The page index is validated and used during the data-binding process.


Data binding Process

The DataBind method is common to all asp.net controls and, for data-bound controls, triggers a refresh of the user interface to reflect the new data. The SqlPager control uses this method to initiate a data retrieval operation based on the values of the SelectCommand and ConnectionString properties. It goes without saying that if any one of these attributes is empty, the procedure terminates. Similarly, if the partner control does not exist, the data binding process is canceled. To find a partner control, the DataBind method uses the FindControl function in the Page class. This shows that the partner control must be a direct child control of the form.

The control that is displayed for paging cannot be any ASP.net server control. It must be a list control or a base data list control. More generally, the partner control must have the DataSource attribute and implement the DataBind method. Controls that can be paginated actually need to meet only those requirements. All controls that inherit ListControl or BaseDataList from Microsoft? NET Framework Meet the first requirement, and all WEB controls meet the DataBind requirements through design. Using the current implementation method, you cannot use the SqlPager control to paging Repeater. Unlike the Repeater control DataList and DataGrid, BaseDataList is not inherited and the functionality of the list control is not provided. The following table lists the controls that you can use SqlPager for paging.

Table 2: Data-bound controls that can be paginated by the SqlPager control

The control description CheckBoxList derived from ListControl and appears as a check box list. DropDownList is derived from ListControl and is displayed as a string Drop-down list. The listbox derives from ListControl and is displayed as a string scrollable list. RadioButtonList is derived from ListControl and is displayed as a list of radio buttons. DataList is derived from BaseDataList and is displayed as a list of templated data items. The DataGrid derives from BaseDataList and is displayed as a table grid for the data item. The DataGrid is the only asp.net control that has a powerful paging engine built into it.
The following code illustrates the data-binding process implemented by the SqlPager control.

public override void DataBind ()
{
Start Data binding Events
Base. DataBinding ();

You must re-create the control after data binding
childcontrolscreated = false;

Make sure the control exists and is a list control
_controltopaginate = Page.findcontrol (controltopaginate);
if (_controltopaginate = null)
Return
if (!) ( _controltopaginate is BaseDataList | | _controltopaginate is ListControl))
Return

Make sure you have enough connection information and specify the query
if (ConnectionString = = "" | | SelectCommand = "")
Return

Get Data
if (Pagingmode = = pagingmode.cached)
Fetchalldata ();
Else
Fetchpagedata ();

Binding data to a partner control
BaseDataList Basedatalistcontrol = null;
ListControl ListControl = null;
if (_controltopaginate is basedatalist)
{
Basedatalistcontrol = (basedatalist) _controltopaginate;
Basedatalistcontrol.datasource = _datasource;
Basedatalistcontrol.databind ();
Return
}
if (_controltopaginate is ListControl)
{
ListControl = (ListControl) _controltopaginate;
ListControl.Items.Clear ();
Listcontrol.datasource = _datasource;
Listcontrol.databind ();
Return
}
}
Invokes a different fetch routine based on the value of the Pagingmode property. In any case, the result set is bound to an instance of the PagedDataSource class. This class provides a number of features for paging data. In particular, when the entire dataset is stored in the cache, the class automatically retrieves the records for the current page and returns a Boolean value to provide information about the first and last pages. The internal structure of this class will be introduced later. In the list above, the helper's PagedDataSource object is represented by the _datasource variable.

The SqlPager control then calculates the type of the partner control and binds the contents of the PagedDataSource object to the DataSource property of the partner control.

In some cases, the DataBind method above also sets the ChildControlsCreated property back to False. So, why do you do it?

When the page that contains the paging program returns, all the controls are re-created, and the paging program is no exception. Typically, all controls and their child controls are created before the page is ready to be displayed. The protected EnsureChildControls method is invoked before each control receives a ONPRERENDER notification, so that each control can build its own control tree. After this event occurs, the data binding process completes and the new data is stored in the cache.

However, when the page returns (that is, the user clicks to change the page) by clicking a constituent control of the paging program, the control tree of the component page program is born, and the display stage is far from being reached. In particular, when working with related server-side events, you must build the control tree and therefore build the control tree before data binding begins. The difficulty is that data binding modifies the page index, which must be reflected in the user interface. If you do not take some action, the page index in the paging program will not be refreshed when the user switches to another page.

There are various ways to solve this problem, but it is important to understand the problem and its real cause. You can avoid building the control tree and generating all the output in the Render method. Alternatively, you can modify the part of the tree that is affected by the data-binding changes. This article selects the third method, which requires less code, and resolves the problem regardless of which part of the control's user interface is affected by the data-binding changes. By setting the ChildControlsCreated property to False, you can invalidate any control tree that you previously created. This will re-create the control tree before it is displayed.


Paging engine

The SqlPager control supports two methods of retrieving data-caching and non-caching. If you take the former, the Select command executes as is, and the entire result set is bound to the data source object that is paginated internally. The PagedDataSource object automatically returns records that are appropriate for a particular page. The PagedDataSource class is also the system component that runs behind the DataGrid default paging mechanism.

Retrieving all records but displaying only a few records that fit the page is often not a sensible way to do this. Because of the stateless nature of WEB applications, it is true that a large number of queries can be run each time a page is requested. To make the operation effective, the cached data retrieval method must rely on some kind of caching object, and the cache object of ASP.net is a good candidate. The use of caching techniques speeds up the application, but the data snapshots it provides do not reflect the latest changes. In addition, it needs to use more memory on the WEB server. And the absurd thing is, if a lot of data is cached by the session, it may even cause a lot of problems. The Cache container is global to the application, and a session-specific project name is generated if the data is stored by session.

The Cache object is above full support for expiration policies. In other words, the data stored in the cache can be released automatically after a period of time. The following code illustrates a private method in the SqlPager class that is used to fetch data and store it in the cache.

private void Fetchalldata ()
{
Find data in asp.net Cache
DataTable data;
data = (DataTable) page.cache[cachekeyname];
if (data = null)
{
Modify SelectCommand using order-by information
Adjustselectcommand (TRUE);

Go to database if data is out of date or has never been fetched
SqlDataAdapter adapter = new SqlDataAdapter (SelectCommand, ConnectionString);
data = new DataTable ();
Adapter. Fill (data);
Page.Cache.Insert (cachekeyname, data, NULL,
DateTime.Now.AddSeconds (CacheDuration),
System.Web.Caching.Cache.NoSlidingExpiration);
}

To configure a paging data source component
if (_datasource = null)
_datasource = new PagedDataSource ();
_datasource.datasource = data. DefaultView;
_datasource.allowpaging = true;
_datasource.pagesize = ItemsPerPage;
TotalPages = _datasource.pagecount;

Make sure the page index is valid
Validatepageindex ();
if (CurrentPageIndex = = 1)
{
_datasource = null;
Return
}

Select the page you want to view
_datasource.currentpageindex = CurrentPageIndex;
}
The control and the requested cache item name are unique. It includes the URL of the page and the ID of the control. In the specified time (in seconds), the data is bound to the cache. To expire a project, you must use the Cache.Insert method. The following simpler code adds a project to the cache, but does not include any expiration policies.

Page.cache[cachekeyname] = data;
The PagedDataSource object gets the data to be paginated through its DataSource property. It is noteworthy that the DataSource property of the PagedDataSource class accepts only IEnumerable objects. The DataTable does not meet this requirement, which is why the DefaultView attribute is taken.

The SelectCommand property determines which queries run on the SQL Server database. This string is best select-from-where form. The ORDER BY clause is not supported and will be deleted if the clause is specified. This is exactly what the Adjustselectcommand method does. Use the SortField property to specify any sort information. The Adjustselectcommand method itself adds a correct order BY clause based on the value of the SortField. Is there any reason to do so?

When the paging program works in noncached mode, the original query is modified to ensure that only the records for the current page are retrieved. The actual query text executed on SQL Server will take the following form.

SELECT * FROM
(SELECT top ItemsPerPage * FROM
(SELECT top Itemsperpage*currentpageindex * FROM
(SelectCommand) As T0
ORDER by SortField ASC) as T1
ORDER by SortField DESC) as T2
ORDER BY SortField
The query compensates for the flaw in the rownum clause in SQL Server 2000 and reorder the records so that only the "n" Blocks of the X item are sorted correctly and returned. You can specify the underlying query that the paging program breaks down into several smaller pages. Only records that are appropriate for a page are returned. As you can see, in addition to the query commands, the above query needs to handle the sort fields. This is why additional SortField properties have been added. The only drawback to this code is that the default is sorted in ascending order. By making the ASC/DESC keyword parameterized, you can make this code truly perfect:

private void Fetchpagedata ()
{
A validated page index is required to get the data.
You also need the actual number of pages to validate the page index.
Adjustselectcommand (FALSE);
Virtualrecordcount countinfo = Calculatevirtualrecordcount ();
TotalPages = Countinfo.pagecount;

Verify page numbers (make sure CurrentPageIndex is valid or "1")
Validatepageindex ();
if (CurrentPageIndex = = 1)
Return

Prepare and Run commands
SqlCommand cmd = PrepareCommand (countinfo);
if (cmd = null)
Return
SqlDataAdapter adapter = new SqlDataAdapter (cmd);
DataTable data = new DataTable ();
Adapter. Fill (data);

To configure a paging data source component
if (_datasource = null)
_datasource = new PagedDataSource ();
_datasource.allowcustompaging = true;
_datasource.allowpaging = true;
_datasource.currentpageindex = 0;
_datasource.pagesize = ItemsPerPage;
_datasource.virtualcount = Countinfo.recordcount;
_datasource.datasource = data. DefaultView;
}

In noncached mode, the PagedDataSource object does not provide an entire data source, so the total number of pages to be paginated cannot be computed. You must then mark the AllowCustomPaging property and provide the actual number of records in the data source. Typically, the actual quantity is retrieved using the SELECT COUNT (*) query. This model is almost identical to the custom paging of the DataGrid. In addition, the current page index selected in the PagedDataSource object is typically 0 because one page of records has actually been stored.

The implementation method of the SqlPager control is introduced here, let's take a look at how it is used.


Using the SqlPager control

Suppose there is a sample page that contains a ListBox control. To use a paging program, make sure that the. aspx page correctly registers the assembly for the control.

<%@ Register tagprefix= "Expo" namespace= "DevCenter" assembly= "SqlPager"%>
The markup for the control depends on the properties that are actually set. The following markup is a reasonable example:

<asp:listbox runat= "Server" id= "ListBox1" width= "300px" height= "168px"
Datatextfield= "CompanyName"/>
<br>
<expo:sqlpager runat= "Server" id= "SqlPager1" width= "300px"
Controltopaginate= "ListBox1"
Selectcommand= "SELECT CustomerID, CompanyName from Customers"
Connectionstring= "Server=localhost;database=northwind; Uid= ... "
Sortkeyfield= "CompanyName"/>
<br>
<asp:button runat= "Server" id= "LoadFirst1" text= "Load first page"/>
In addition to the paging program, the page also contains a list box and a button. The list box displays the contents of each page, and the button is used only for the first time to populate the list box. The button has a click event handler, which is defined as follows.

private void Loadfirst1_click (object sender, EventArgs e) {
Sqlpager1.currentpageindex = 0;
Sqlpager1.databind ();
}



A more interesting example can be generated by using the DataList control. The goal is to use the paging program to browse the personal records of each Northwind employee. The DataList as shown in the following list.

<asp:datalist runat= "Server" id= "DataList1" width= "300px"
Font-names= "Verdana" font-size= "8pt" >
<ItemTemplate>
<table bgcolor= "#f0f0f0" style= "font-family:verdana;font-size:8pt;" >
<tr> <td valign= "Top" >
<b> <%# DataBinder.Eval (Container.DataItem, "LastName") + "," +
DataBinder.Eval (Container.DataItem, "FirstName")%> </b>
</td> </tr>

<tr> <td>
<span style= "Color:blue;" > <i>
<%# DataBinder.Eval (Container.DataItem, "Title")%> </i> </span>
<p> '/>
<%# DataBinder.Eval (Container.DataItem, "Notes")%>
</td> </tr>
</table>
</ItemTemplate>
</asp:datalist>
The first line of the table shows the name and title of the employee, followed by a photo with a note around the photo. The photo is retrieved using a specific. aspx page, and returns the JPEG data obtained from the database.

A paging program can be placed anywhere on the page. In this case, place it above the collaborators DataList control and next to the partner control.



Does it make sense to use the SqlPager control with the DataGrid control? This depends on the circumstances. The DataGrid has worked with an embedded paging engine that is based on the PagedDataSource object used in this article. Therefore, you do not need to use SqlPager if you want to page through a single collection of records that is displayed in a tabular format. However, for important/complex scenarios, it is not a far-fetched idea to use the two controls together. For example, if you want to add a DataGrid to the front of a screenshot to display an order that is managed by an employee, you can place two related paging engines on the same page, one to page the staff, and the other to scroll the related orders.

Summary

Regardless of which type of application you are building (Web application, Microsoft? Windows? Application or Web service, it is difficult for you to download and cache the entire data source that you want to display. Sometimes the test environment makes you believe that the solution is great and desirable. But the test environment can also be misleading. The size of the data source is critical, and the larger the size of the application, the more critical the size of the data source is.

In ASP.net, only the DataGrid control has built-in paging functionality. However, the paging engine is implemented by fairly boilerplate code that can be popularized and used for multiple different controls as long as a small amount of processing is done. This goal is achieved by the SqlPager control described in this article. It focuses on downloading data, dividing it into multiple pages and displaying it through a partner control. The control can retrieve and cache the entire dataset, or only a few records to be displayed in the selected page in SQL Server. I'm talking about SQL Server, which is another point. SqlPager can only be used with SQL Server and cannot be used to retrieve data through OLE DB or ODBC. Nor can you use it to access Oracle or DB2 archives.

To generate a true general-purpose SQL paging program component, you should form a data access layer and generate a factory class that can create connections, commands, and adapters with the appropriate data provider. Also, be aware that setting up a paging engine for a variety of SQL sources is the worst practice. The methods described here apply only to SQL Server 7.0 and later versions. The TOP clause has different characteristics in different environments. Using server cursors and temporary tables, it can be applied to a larger range of DBMS systems. But that will make the code more complex.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.