1. Introduction
In the preceding tasks, we have created some simple but practical custom controls, but they can only be rendered according to fixed settings, some key features are missing-Data Binding and sometimes support template settings for more flexible control. ASP. NET data binding controls are divided into three types:
- Simple data binding: simple data binding binds an object to a property of a control. The data source is only bound to a single data item, rather than a data item list. Simple data binding is completed using a data binding expression. The data binding expression is any executable encapsulated by <% #... %>.Code.
- List Control: A list control displays a list of data items on a fixed user interface. Common List controls include the radiobuttonlist control, the checkboxlist control, and the bulletedlist control introduced in ASP. net2.0.
- Complex data binding: a complex data binding control is usually a combination control that displays a group of data items. They have a flexible rendering mechanism. For example, the gridview control is a complex data binding control.
To enable the star control to display data through a data source during use, you need to enable the control to bind data. When using the data binding method, the Code may look as follows:
Private void binddata () {datatable table = new datatable (); datacolumn Col = new datacolumn ("comment", typeof (string); table. columns. add (COL); Col = new datacolumn ("score", typeof (INT); table. columns. add (COL); datarow ROW = table. newrow (); row [0] = "vista"; row [1] = 3; table. rows. add (ROW); table. acceptchanges (); star. datasource = table; star. datatextfield = "comment"; star. datavaluefield = "score"; star. databind ();}
2. Analysis
Before starting the list control, let's discuss simple data binding. The star control developed several times ago is a simple data binding control. We can directly assign values to one of its attributes using a data binding expression, for example, in starttest. write the following code in aspx to use the custom control:
<CC: Star id = "star" runat = "server" score = "4" comment = "<% # datetime. Now %>" font-size = "12px"/>
Preview on the page -- unfortunately, the current date is not displayed on the page. This is because any data binding expression defined on the page is calculated only after the databound method is called. You can call the databind method of a page object or the databind method of a specific control. In fact, if you call the databind method of a page object, it recursively calls the databind Method on all controls defined in the page. This means that if multiple data binding expressions are used on the page, you 'd better call the page. databind method to perform data binding.
If you want to know what operations are performed at the underlying layer during data binding, you can enable ASP. NET debugging and change the temporary file directory. Modify the complcation configuration section in Web. config as follows:
<Compilation DEBUG = "true" tempdirectory = "C: \ Web"> ...... ...... </Complation>
The preceding configuration starts debugging and sets the temporary directory to C: \ Web (if the temporary file of the tempdirectory attribute is not set, it will be placed in the default % WINDOWS % \ Microsoft. net \ framework \ % version % \ temporary ASP.. Net Files directory ). After previewing the startest. ASPX page in the browser, you can find the two branch class definitions of startest in the temporary directory. One defines the post code and the other is used to generate the ASPX page. In the class file that generates the ASPX page, you can find the __ buildcontrolstar method (in fact, there are a series of __ buildcontrolxxx methods, xxx corresponds to the Control ID), which contains the following code:
CTRL. databinding + = new system. eventhandler (this. databindingstar );
Correspondingly, you can find the @ __databindingstar method in this file. The method is as follows:
Public void @__ databindingstar (Object sender, system. eventargs e) {controllibrary. star databindingexpressionbuildertarget; system. web. UI. page container; databindingexpressionbuildertarget = (controllibrary. star) (sender); Container = (system. web. UI. page) (databindingexpressionbuildertarget. bindingcontainer); # Line 13 "E: \ Documents ents and Settings \ holywolf \ My Documents ents \ books \???? \?????????? \ Controlsolution \ WEB \ startest. aspx "databindingexpressionbuildertarget. Comment = system. Convert. tostring (datetime. Now, system. Globalization. cultureinfo. currentculture); # line default # Line hidden}
If the data binding expression does not match the expected type, a compilation error is usually returned. However, if the expected type is string, the parser uses the convert. tostring method to implement standard conversion.
Next we will discuss how to bind star controls with data. First we will look at the data binding class hierarchy in ASP. net2.0:
As you can see, all classes are inherited from the basedataboundcontrol class, which is the base class of the ASP. net2.0 data binding control. The basedataboundcontrol class defines how to bind data and how to verify the bound data. It also defines two data source attributes: datasource attribute used to enumerate data and performanceid attribute used for data source controls.
The datasource property accepts an object that implements the ienumerable interface (for example, set) or ilistsource interface (for example, datatable). After this attribute is set, you must call this control or the databind method of the page to fill the data in the control.
The databoundcontrol class inherits from the basedataboundcontrol class. This class provides an important method for calling the mdatabinding method. When writing a custom control derived from the databoundcontrol class, you need to write this method to load data, the method is defined as follows:
Protected virtual void extends mdatabinding (ienumerable data ){...... ......}
When creating a custom data binding control, you generally need to process the following:
- Define related dataxxxfield to specify the ing to the data source
- Add data item attributes and manually manage view statuses for higher efficiency
- Reload the mongomdatabinding method to read data from the data source and cache it to the data item.
- Display Control Based on the saved values in the data item
Based on the above analysis, you can modify the original Star control to inherit from databoundcontrol to obtain the ability to read data from the data source.
3. Implementation
3.1 Add the stardataitem class to the controllibrary class library in the solution as a data item to save data. In order to manage the view status, this class implements the istatemanager interface:
Using system; using system. Web. UI; namespace controllibrary {public class stardataitem: istatemanager {}}
3.2 add score and comment attributes in the class and add constructor:
Public String comment {Get; set;} public int score {Get; set;} public stardataitem () {comment = string. empty; score = 0;} public stardataitem (string comment, int score) {comment = comment; score = score ;}
3.3 implement the istatemanager interface to manage the view status:
Private bool _ mark; Public bool istrackingviewstate {get {return _ mark;} public object saveviewstate () {pair P = new pair (comment, score); Return P ;} public void loadviewstate (Object savedstate) {If (savedstate! = NULL) {pair P = (pair) savedstate; Comment = convert. tostring (P. first); score = convert. toint32 (P. second) ;}} public void trackviewstate () {_ mark = true ;}
3.4 add the databoundstar class, which inherits the databoundcontrol class:
Using system; using system. collections; using system. Web. UI; using system. Web. UI. webcontrols; namespace controllibrary {public class databoundstar: databoundcontrol {}}
3.5 define data item attributes in this class (stardataitem type ):
Private stardataitem _ data; Public stardataitem dataitem {get {If (_ DATA = NULL) _ DATA = new stardataitem (); If (istrackingviewstate) _ data. trackviewstate (); Return _ DATA ;}}
3.6 add datatextfield and datavaluefield attribute ing to the data source for the class:
Public Virtual string datavaluefield {get {object o = viewstate ["datavaluefield"]; return O = NULL? String. empty: (string) O;} set {viewstate ["datavaluefield"] = value;} Public Virtual string datatextfield {get {object o = viewstate ["datatextfield"]; return o = NULL? String. Empty: (string) O;} set {viewstate ["datatextfield"] = value ;}}
3.7 rewrite the performdatabinding method to read data from the data source according to the ing and fill the data into the data items:
Protected override void extends mdatabinding (ienumerable data) {If (Data = NULL) return; ienumerator E = data. getenumerator (); E. movenext (); If (! String. isnullorempty (datatextfield) dataitem. Comment = convert. tostring (databinder. getpropertyvalue (E. Current, datatextfield); If (! String. isnullorempty (datavaluefield) dataitem. Score = convert. toint32 (databinder. getpropertyvalue (E. Current, datavaluefield ));}
This method receives parameters of the ienumerable type for overlapping access to data in the data source. The databinder class is used to read data in the data source. This class has a practical getpropertyvalue method, this method is used to read values from the data source based on property reflection. In this example, datatextfield and datavaluefield are passed to read comments and scores.
3.8 override the createchildcontrols method and call the createcontrolhierarchy method to create a child control hierarchy:
Protected override void createchildcontrols () {base. createchildcontrols (); createcontrolhierarchy ();} protected virtual void createcontrolhierarchy () {Table = new table (); tablerow ROW = new tablerow (); table. rows. add (ROW); tablecell comment = new tablecell (); createcomment (comment); row. cells. add (comment); tablecell stars = new tablecell (); createstars (stars); row. cells. add (stars); this. controls. add (table );}
3.9 As shown above, the createcomment and createstars methods are called when the child control is created to create comments and star patterns (resource files are still used), and relevant data is read by the dataitem attribute, the implementation of these two methods is as follows:
Private void createcomment (tablecell cell) {label LBL = new label (); LBL. TEXT = dataitem. comment; cell. controls. add (LBL);} private void createstars (tablecell cell) {string starpath = page. clientscript. getwebresourceurl (this. getType (), "controllibrary.image.stars.gif"); Panel panbg = new Panel (); panbg. style. add (htmltextwriterstyle. width, "80px"); panbg. style. add (htmltextwriterstyle. height, "16px"); panbg. style. add (htmltextwriterstyle. textalign, "Left"); panbg. style. add (htmltextwriterstyle. overflow, "hidden"); panbg. style. add (htmltextwriterstyle. position, "relative"); panbg. style. add (htmltextwriterstyle. backgroundimage, starpath); panbg. style. add ("background-position", "0px-32px"); panbg. style. add ("background-repeat", "Repeat-X"); cell. controls. add (panbg); Panel pancur = new Panel (); string width = dataitem. score * 16 + "PX"; pancur. style. add (htmltextwriterstyle. width, width); pancur. style. add (htmltextwriterstyle. height, "16px"); pancur. style. add (htmltextwriterstyle. backgroundimage, starpath); pancur. style. add ("background-position", "0px 0px"); pancur. style. add ("background-repeat", "Repeat-X"); panbg. controls. add (pancur );}
3.10 rewrite the saveviewstate and loadviewstate methods to save the dataitem data item to the view State and restore it correctly:
Protected override object saveviewstate () {object o = base. saveviewstate (); pair P = new pair (); p. first = O; p. second = dataitem. saveviewstate (); Return P;} protected override void loadviewstate (Object savedstate) {If (savedstate! = NULL) {pair P = (pair) savedstate; base. loadviewstate (P. First); dataitem. loadviewstate (P. Second );}}
3.11 rewrite the render method to render the control:
Protected override void render (htmltextwriter writer) {preparecontrolforreader (); base. render (writer);} private void preparecontrolforreader () {If (this. controls. count <1) return; Table = (table) This. controls [0]; table. cellspacing = 0; table. cellpadding = 0 ;}
3.12 Add a page to a Web site and declare and define custom controls:
<CC: databoundstar id = "star" runat = "server"/>
3.13 write code similar to the code starting from this task to execute Data Binding and preview the result in the browser.
4. Summary
In this task, we once again added a new feature-data binding for the star control. To achieve this purpose, the custom control inherits the databoundcontrol class and implements an important method called performdatabinding, use the ienumerable parameter of this method to iteratively access the data source and call databinder. the getpropertyvalue method obtains the ing value of the data source. Finally, the stardataitem class is defined as the property of the custom control to save the data reasonably. In the next task, we will develop a list control.
The following background image is provided:
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