Datalist for implementing the paging function on the tenth day of ASP. NET custom control (this series of articles is attached to the PDF version)

Source: Internet
Author: User
1. Introduction

In ASP. in net, datalist can be used to display data. We can customize its templates to implement rich formats. However, if there is no shortage in the United States, datalist does not support paging by default, of course, we can write a user control to implement the paging function, but this solution is still not very good, we hope to use a common ASP.. NET Server controls are the same. You only need to place a datalist and set the paging style to output the paging link.

In the previous task, we created the datapager class to separate the paging operation from the gridview. This task will try to reuse the datapager class to add the paging feature for datalist.

2. Analysis

When developing a custom gridview control, you can add a button with a specific commandname to the control to implement pagination, but it is not applicable to datalist, because datalist cannot receive client-side sending events, this is also a difference between the datalist class and the gridview class-the datalist class does not implement the ipostbackeventhandler interface. To enable datalist to receive client-side sending back and trigger paging events, you need to enable custom datalist to implement the ipostbackeventhandler interface, and use the Custom Event parameter class to transmit page number information when an event is triggered.

The ipostbackeventhandler interface defines the methods that ASP. NET Server controls must implement to handle sending back events. Its members only have one method:

 
VoidRaisepostbackevent (StringEventargument)

This method is implemented by a class so that the server control can process events triggered when a form is sent to the server.

Next, we need to consider how to cause a sending event on the client, that is, how to generate a sending script. The clientscriptmanager class is used here. This class appears as a clientscript attribute of the page class. The client script is generated by calling the getpostbackclienthyperlink method of this class to cause sending back. This method has two forms of overloading:

    • Getpostbackclienthyperlink (control, string)

Get a reference and add javascript: at the beginning of it. You can use this reference in client events and use this reference with the specified event parameters, to send back to the server of the specified control.

    • Getpostbackclienthyperlink (control, String, Boolean)

Get a reference and add javascript: at the beginning of it. This reference can be used to send back to the server of the specified control in client events, use the specified event parameters and a Boolean value indicating whether to register the callback for event verification.

The first parameter specifies the Server Control for sending and receiving requests. The second parameter indicates the parameter passed to the server control. The third parameter indicates whether to register the event.

Next, write the implementationCode.

3. Implementation

3.1 create a datalistpager class that inherits from the datapager class and adds the send-back script for the paging link:

Public class datalistpager: datapager {public datalistpager (pagersettings setting, int pageindex, int recordcount, int pagesize, datalist DAL): Base (setting, pageindex, recordcount, pagesize) {linkbutton BTN = NULL; int _ pagecount = recordcount % pagesize = 0? Recordcount/pagesize: recordcount/pagesize + 1; int index; foreach (Control in this. controls) {If (control is linkbutton) {BTN = (linkbutton) control; If (BTN. enabled) {string argvalue = BTN. commandargument; bool isint = int. tryparse (argvalue, out index); string Arg = string. empty; If (isint) {index --;} else {Switch (argvalue) {Case constant. first_page: Index = 0; break; Case Co Nstant. prev_page: Index = pageindex-1 <0? 0: pageindex-1; break; Case constant. next_page: Index = pageindex + 1> _ pagecount-1? _ Pagecount-1: pageindex + 1; break; Case constant. last_page: Index = _ pagecount-1; break;} Arg = constant. page_argument + constant. argument_splitter + index; BTN. attributes. add (htmltextwriterattribute. href. tostring (), Dal. page. clientscript. getpostbackclienthyperlink (DAL, ARG ));}}}}}

3.2 Create a datalist class, inherit from the default datalist class, and implement the ipostbackeventhandler interface:

 
[Toolboxdata (@ "<{0}: datalist runat = 'server'> </{0}: datalist>")] [parsechildren (true)] [persistchildren (false)] public class datalist: system. web. UI. webcontrols. datalist, ipostbackeventhandler {}

3.3 define the datalist attribute and save the page settings:

Public int recordcount {get {object o = viewstate ["recordcount"]; return O = NULL? 0: convert. toint32 (o) ;}set {viewstate ["recordcount"] = value ;}} Public Virtual int pageindex {get {object o = viewstate ["pageindex"]; return o = NULL? 0: convert. toint32 (o) ;}set {viewstate ["pageindex"] = value ;}} [defaultvalue (10)] public Virtual int pagesize {get {object o = viewstate ["pagesize"]; return O = NULL? 10: convert. toint32 (o) ;}set {viewstate ["pagesize"] = value ;}} private pagersettings _ settings; [designerserializationvisibility (designerserializationvisibility. content)] [persistencemode (persistencemode. innerproperty)] public pagersettings {get {If (_ settings = NULL) _ settings = new pagersettings (); If (base. istrackingviewstate) (istatemanager) _ settings ). trackviewstate (); Return This. _ settings ;}} public bool enablepaging {get {object o = viewstate ["enablepaging"]; return O = NULL? False: Convert. toboolean (o);} set {viewstate ["enablepaging"] = value ;}}

3.4 create a custom event class and save the new page number:

 
Public class datalistpageeventargs: eventargs {public int newpageindex {Get; Set ;}}

3.5 create events and auxiliary methods in the datalist class:

 
Public event eventhandler <datalistpageeventargs> pageindexchanging; protected virtual void onpageindexchanging (Object sender, datalistpageeventargs e) {If (pageindexchanging! = NULL) {pageindexchanging (sender, e );}}

3.6 compile the rendercontent method, which implements the core paging operations. By instantiating the datalistpager class instance, add the link that triggers the send-back operation to the current datalist:

Protected override void rendercontents (htmltextwriter writer) {This. renderbegintag (writer); If (enablepaging) {Table = new table (); tablerow ROW = new tablerow (); table. rows. add (ROW); tablecell cell = new tablecell (); row. renderbegintag (writer); cell. renderbegintag (writer); base. rendercontents (writer); cell. renderendtag (writer); row. renderendtag (writer); tablerow rowpager = new tablerow (); datalistpager pager = new datalistpager (pagersettings, pageindex, recordcount, pagesize, this); rowpager. cells. add (PAGER); rowpager. renderbegintag (writer); pager. rendercontrol (writer); rowpager. renderendtag (writer);} else {base. rendercontents (writer);} This. renderendtag (writer );}

3.7 compile the implementation of the raisepostbackevent method in the iposteven thandler interface to determine the current event parameters and trigger a page feed event:

Public void raisepostbackevent (string eventargument) {string [] ARGs = eventargument. split (constant. argument_splitter); If (ARGs = NULL | args. length <1) return; string name = ARGs [0]; If (name = constant. page_argument) {int Index = 0; string argvalue = ARGs [1]; bool isint = int. tryparse (argvalue, out index); If (isint) {datalistpageeventargs Arg = new datalistpageeventargs (); arg. newpageindex = index; onpageindexchanging (this, ARG );}}}

3.8 rewrite the saveviewstate and loadviewstate methods to define how to save and read the view State:

Protected override object saveviewstate () {object o = base. saveviewstate (); object osetting = (istatemanager) pagersettings ). saveviewstate (); pair P = new pair (O, osetting); Return P;} protected override void loadviewstate (Object savedstate) {If (savedstate! = NULL) {pair P = (pair) savedstate; base. loadviewstate (P. first); (istatemanager) pagersettings ). loadviewstate (P. second);} else {base. loadviewstate (null );}}

3.9 create a test page on the website and declare and define the custom datalist:

<CC: datalist id = "daldata" runat = "server" enablepaging = "true" pagesize = "10" onpageindexchanging = "daldata_pageindexchanging" pagersettings-firstpagetext = "???? "> <Itemtemplate> <Table class =" data "cellpadding =" 0 "cellspacing =" 1 "border =" 0 "> <tr> <TD> <asp: label id = "lblid" runat = "server" text = '<% # eval ("ID") %>'> </ASP: label> </TD> <asp: Label id = "lblname" runat = "server" text = '<% # eval ("name ") %> '> </ASP: Label> </TD> </tr> </table> </itemtemplate> </CC: datalist>

3.10 compile the binddata method in the post code to load data, and call this method when the page is not sent back to display data:

Protected void page_load (Object sender, eventargs e) {If (! Ispostback) This. binddata ();} private void binddata () {datatable table = new datatable (); datacolumn Col = new datacolumn ("ID"); table. columns. add (COL); Col = new datacolumn ("name"); table. columns. add (COL); For (INT I = daldata. pageindex * daldata. pagesize; I <daldata. pageindex * daldata. pagesize + daldata. pagesize; I ++) {datarow ROW = table. newrow (); row [0] = I; row [1] = "Personnel" + I; table. rows. add (ROW);} daldata. datasource = table; daldata. recordcount = 30; daldata. databind ();}

3.11 compile a datalist page switch event, assign a new page index to datalist, and bind the data:

 
Protected void daldata_pageindexchanging (Object sender, datalistpageeventargs e) {daldata. pageindex = E. newpageindex; this. binddata ();}

3.12 preview the effect in the browser:

4. Summary

In this task, a Javascript script is added to the linkbutton to enable sending back when the client clicks. This is achieved through the getpostbackclienthyperlink method of the clientscriptmanager class. After the submission is triggered, in order to be able to process the sending back event on the server side, the ipostbackeventhandler interface is implemented in the Custom datalist control and the custom page switching event is called in the implementation method, allows developers to bind data based on the new page number. We can see that datalist and gridview have implemented paging, but in a sense, this solution is not elegant enough (often by JavaProgramA word used by the operator to talk about things -_-!!), You can make improvements on your own.

ASP. NET Custom ControlsArticle

Preface

Simple star control on the first day

Star controls with custom styles the next day

On the third day, use the star widget in the control status.

Fold panel custom controls on the fourth day

Star controls that can be scored on the fifth day

Star controls that can be bound to data sources on the sixth day

Develop list controls with rich features on the seventh day

Metric days: displays the data binding controls for multiple entry star rating

The ninth day custom gridview

Datalist that implements the paging function on the tenth day

Download all source code

Download this series of articles in PDF

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.